是否可以使用Typescript将数组的值约束到字符串值的给定子集?

问题描述 投票:1回答:1

考虑:

enum allowedValues {'x','y'}

export interface X {
  evaluation: string[]; // TODO: how to constrain to contain only the values 'x' or 'y';
}

我试着宣布evaluation作为枚举:evaluation: shownEvaluation[];我也试过evaluation: keyof allowedValues;

是否可以使用Typescript将数组的值约束到字符串值的给定子集?

arrays typescript
1个回答
1
投票

是!您需要声明键的联合类型:

type allowedValues = 'x' | 'y';

export interface X {
    evaluation: allowedValues[];
}
© www.soinside.com 2019 - 2024. All rights reserved.