是否有一种 Typescript 方法要求数组至少有一个值?例如:
type value = "1" | "2";
export interface ISomething {
values: value[] // < should be required and have at least one.
}
type value = "1" | "2";
export interface ISomething {
values: [value, ...value[]] // ← this is the non-empty array type
}
const empty: ISomething = { values: [] }
// Type '[]' is not assignable to type '[value, ...value[]]'.
// Source has 0 element(s) but target requires 1.
const oneValue: ISomething = { values: ["1"] }
// all good :)
您可以选择将其提取以用作通用实用程序类型,如下所示:
export type NonEmptyArray<T> = [T, ...Array<T>];
export interface ISomething {
values: NonEmptyArray<value>
}
另一种没有接口的方式:
export type NonEmptyArray<Type> = [Type, ...Array<Type>];
用途:
const arrayOfStrings1: NonEmptyArray<string> = ['x']; // valid
const arrayOfStrings2: NonEmptyArray<string> = ['x', 'y']; // valid
const arrayOfStrings3: NonEmptyArray<string> = ['x', 'y', 'z']; // valid
const arrayOfStrings4: NonEmptyArray<string> = [] // invalid
// Type '[]' is not assignable to type '[string, ...string[]]'.
// Source has 0 element(s) but target requires 1.ts(2322)
试试这个
type value = "1" | "2";
export interface ISomething {
values: {
0: value,
[key: number]: value,
}
}``
您还可以实现一个扩展的接口
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
}