我想将单个数组const fruits = ['banana', 'apple', 'orange']
用作普通数组,并将type
.
我应该能够做到这一点:
const x: fruits // => only accepts 'banana', 'apple' or 'orange'
并且还能够做到这一点:
@IsIn(fruits)
我试图将数组声明为<const>
,例如:
const fruits = <const>['banana', 'apple', 'orange']
type Fruits = typeof fruits[number] // this evaluates to type: "banana" | "apple" | "orange"
但是@IsIn(fruits)
会返回以下错误:
Argument of type 'readonly ["banana", "apple", "orange"]' is not assignable to parameter of type 'any[]'.
The type 'readonly ["banana", "apple", "orange"]' is 'readonly' and cannot be assigned to the mutable type 'any[]'.ts(2345)
所以我想如果我创建了两个数组,一个普通数组和一个只读数组,它应该可以工作。所以我尝试了这个:
const fruits = ['banana', 'apple', 'orange']
const fruits_readonly: <const>[...fruits]
type Fruits = typeof fruits_readonly[number]
但现在Fruits
评估为type: string
而不是type: "banana" | "apple" | "orange"
.