让我们假设我们有一个类型和一个数组:

type Fruit = 'apple' | 'orange' | 'pineapple'

const initialFruits: Fruit[] = ['pineapple', 'apple', 'orange']

如果我try 在赋值之前对数组进行排序,则会得到一个错误:

const initialFruits: Fruit[] = ['pineapple', 'apple', 'orange'].sort()

// Type 'string[]' is not assignable to type 'Fruit[]'.

我发现了一种在排序后保存类型的方法,但它看起来很奇怪:

const initialFruits: Fruit[] = [
  'pineapple' as const,
  'apple' as const,
  'orange' as const
].sort()

有没有更方便的方法来解决这个问题?

推荐答案

数组按Fruit类型排序.

type Fruit = 'apple' | 'orange' | 'pineapple'

const initialFruits: Fruit[] = ['pineapple', 'apple', 'orange'].sort() as Fruit[];

const sortedFruits: Fruit[] = ['pineapple', 'apple', 'orange'].sort((a, b) => {
  return initialFruits.indexOf(a) - initialFruits.indexOf(b);
}) as Fruit[];

Javascript相关问答推荐

一次仅播放一个音频

如何将连续的十六进制字符串拆分为以空间分隔的十六进制块,每个十六进制块包含32个二元组?

. NET中Unix时间转换为日期时间的奇怪行为

扫描qr code后出错whatter—web.js

单击ImageListItemBar的IconButton后,在Material—UI对话框中显示图像

如何在bslib nav_insert之后更改导航标签的CSS类和样式?

WP Bootstrap NavWaker:下拉菜单一次打开所有下拉菜单

映射类型定义,其中值对应于键

未加载css colored颜色 ,无法将div设置为可见和不可见

为什么云存储中的文件不能公开使用?

令牌JWT未过期

使用父标签中的Find函数查找元素

有没有一种直接的方法可以深度嵌套在一个JavaScript对象中?

使用自动识别发出信号(&Q)

如何用javascript更改元素的宽度和高度?

通过跳过某些元素的对象进行映射

JAVASCRIPT SWITCH CASE语句:当表达式为';ALL';

如何在尚未创建的鼠标悬停事件上访问和着色div?

如何在Firebase中读取对象的特定字段?

:host::ng-Deep不将样式应用于material 复选框