打字稿:如何定义一个键,键的值是数组中值的子集?

我想定义一个接口,该接口的键值可以是字符串数组。但是这些字符串只能来自已定义的字符串数组。

类似-

const valueOptions = ['a','b','c',.... 100 more];

interface containerProps {
  key: <array of strings which can only be a subset of valueOptions>
}

请帮助。

dmayahot777 回答:打字稿:如何定义一个键,键的值是数组中值的子集?

您可以提取类型,然后将其映射到您的界面上

// declare "as const" to make it a readonly Array<"a"|"b"|"c"> instead of string[]
const valueOptions = ["a","b","c"] as const;

// Type helper to extract the underlying data type of the array
type StripArray<T extends ReadonlyArray<string>> = T extends ReadonlyArray<infer U> ? U : never; 

type ValueUnion = StripArray<typeof valueOptions>; // ValueUnion = "a"|"b"|"c";

interface Whatever {
    keys: ValueUnion[] // Whatever.keys is Array<"a"|"b"|"c">
}

我在TS游乐场页面上做了很多此类事情,对于快速查看类型并查看实际发生的情况非常有用。

http://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=11&pc=2#code/PTAEBMFMGMBsEMBOlQCJ4GdTQPYDsMAXVUQnUAW3gGsUBLQ0eUZecfWAT1AEFFF4nADzpUAH1QAjcamioAfKDoFCkNqBwAzUEUTKA5gG0AugChcK0ADd4sAK6QA8gAdCdfFgC8oQ6IA0aNIBsqjGTFgWRADcpqYgoAAqnM4oABaQsCmIpOSQAB6EAtCMhOmgdnhQiFwGEPCEzITJKFqkZUgCnKZNKaAAyoV0znydQgmg+aqVWABKaux4XCOCQroG8ore45OQ06BzbBycy8LKmpDZAKqKAPygl6AAXKB4kFYXUaCxPSgAarYOS54dx4UDeAZ6Yb8FY-Vo2exOVwgjDyT7xf4IoEgsFoeAyaQSOQxUzKVSITTwaAoADqqXqbwuoAA3qZQGzQLROBhnhjAcD8CZQPFafT3ogAHScrB0LAnER4iQEkLyUwAXyAA

,

首先使用<const>断言锁定数组项,使其成为受限集合。

现在您可以使用索引值的类型了。例如:

  • typeof valueOptions[0]只能是"a"
  • typeof valueOptions[1]只能是"b"
  • typeof valueOptions[number]可以是"a","c"

因此,根据您的情况,您将使用number,因为您不查找任何特定的索引:

const valueOptions = <const>["a","c"]; // lock it down with const assertion

interface IContainerProps {
  key: typeof valueOptions[number]; // typeof index members of valueOptions
}

const a: IContainerProps = {
  key: "b"
};

因此,对于小的子集,您可以创建联合类型:

interface IContainerProps {
  key: typeof valueOptions[1] | typeof valueOptions[2];
}

const a: IContainerProps = {
  key: "b"
};

const b: IContainerProps = {
  key: "c"
};
,
enum KeyOptions {

 A = ‘a’,B = ‘b’

}

interface ArrayAndStuff {

 key: KeyOptions[];

}
本文链接:https://www.f2er.com/3101129.html

大家都在问