我想在Typescript中实现这一点:

type animals = 'cat' | 'dog'

let selectedAnimals: animals[] = ['cat']

selectedAnimals = [ // <- Type 'string[]' is not assignable to type 'animals[]'
    ...selectedAnimals,
    ...(condition ? ['cat'] : [])
]

Link.

下面的方法很有效,但是有没有比使用as animals更好的方法呢?

type animals = 'cat' | 'dog'

let selectedAnimals: animals[] = ['cat']

selectedAnimals = [
    ...selectedAnimals,
    ...(['cat' as animals]),
    ...(['wednesday' as animals]) // <- this also compiles
]

推荐答案

您可以将as const添加到['cat'],使其类型为readonly ["cat"],而不是string[],代码将在编译时不会丢失类型安全性.这也将防止包括非动物数组:

type animals = 'cat' | 'dog'

let selectedAnimals: animals[] = ['cat']

selectedAnimals = [
    ...selectedAnimals,
    ...(['cat'] as const),
    // ...(['wednesday'] as const) // <- will fail
]

TypeScript playground

或者,您可以将as const添加到单个元素中,例如[`cat` as const],它将数组键入"cat"[].(Playground)

Typescript相关问答推荐

如何在Typescript 中输入两个相互关联的变量?

学习Angular :无法读取未定义的属性(正在读取推送)

如何使用Zod使一个基于其他字段值的字段为必填字段?

Next.js错误:不变:页面未生成

如何在Angular 12中创建DisplayBlock组件?

匿名静态类推断组成不正确推断

通过按键数组拾取对象的关键点

垫表页脚角v15

在列表的指令中使用intersectionObservable隐藏按钮

如何编辑切片器以使用CRUD调用函数?

有没有办法传递泛型类型数组,以便推断每个元素的泛型类型?

如何键入并类型的函数&S各属性

Angular NG8001错误.组件只能在一个页面上工作,而不是在她的页面上工作

为什么看起来相似的代码在打字时会产生不同的错误?

带有';的类型脚本嵌套对象可选属性错误满足';

使用泛型以自引用方式静态键入记录的键

TypeScript:方法获胜';t接受较窄类型作为参数

如何确定剧作家中给定定位器的值?

从 npm 切换到 pnpm 后出现Typescript 错误

redux-toolkit、createAsyncThunk 错误