typescript 如何创建一个类型的数组值?

64jmpszr  于 2022-11-30  发布在  TypeScript
关注(0)|答案(2)|浏览(122)

我想创建一个类型,该类型只接受数组值的特定组合,而不考虑其顺序。
例如:

const acceptedCombo = ['a', 'b'];

function foo(param: MyType) {}

// Possible combos:
['a', 'b'] // OK
['b', 'a'] // OK
['a', 'b', 'c'] // TypeError - "c" is extra
['a'] // TypeError - "b" is missing

如何定义MyType

btxsgosb

btxsgosb1#

你可以这样做:

type MyType = [string, string];
xurqigkl

xurqigkl2#

以下是您可以定义的类型:

type Type = [string, string]

const v1: Type = ['a', 'b'] // OK
const v2: Type = ['b', 'a'] // OK
const v3: Type = ['a', 'b', 'c'] // Type '[string, string, string]' is not assignable to type 'Type'
const v4: Type = ['a'] // Type '[string]' is not assignable to type 'Type'.

Playground

相关问题