是否有一种Typescript方式要求数组至少需要一个值?例如:
type value = "1" | "2";
export interface ISomething {
values: value[] // < should be required and have at least one.
}
答案 0 :(得分:1)
尝试一下
type value = "1" | "2";
export interface ISomething {
values: {
0: value,
[key: number]: value,
}
}``
答案 1 :(得分:0)
您还可以实现扩展Array
的接口:
type value = "1" | "2";
interface IValueArray extends Array<value> {
0: value; // ensure that at least one 'value' is present
}
export interface ISomething {
values: IValueArray
}
const something1: ISomething = {
values: ['1']
}
const something2: ISomething = {
values: [] // type error
}