【发布时间】:2020-03-02 02:19:34
【问题描述】:
我想将单个数组 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"。
【问题讨论】:
标签: typescript class-validator