(以下假设您使用TS3.0或更高版本)
TypeScript 支持以下概念字符串文字类型 https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types也元组类型 https://www.typescriptlang.org/docs/handbook/basic-types.html#tuple,这样就有可能得到你的值a
拥有type ['ONE', 'TWO', 'THREE']
以及value ['ONE', 'TWO', 'THREE']
, 像这样:
const a: ['ONE', 'TWO', 'THREE'] = ['ONE', 'TWO', 'THREE'];
(稍后将提供一种不太冗余的方法来实现这一点):
然后你可以代表想要的类型b
作为从键到与键完全匹配的值的映射,使用映射类型 https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types:
type SameValueAsKeys<KS extends string[]> = { [K in KS[number]]: K };
可以这样使用:
const b: SameValueAsKeys<typeof a> = a.reduce((acc, type) => ({ ...acc, [type]: type }), {} as any);
b.ONE; // property type is "ONE"
b.TWO; // property type is "TWO"
b.THREE; // property type is "THREE"
注意编译器如何知道这一点b
有三把钥匙,"ONE"
, "TWO"
, and "THREE"
,并且值与键相同。
所以 TypeScript 当然支持这种类型的动态类型。不幸的是,正如我上面展示的那样,使用起来有点乏味。减少这种烦恼的一种方法是添加一些辅助函数,允许编译器推断正确的类型,或者至少将类型断言隐藏在库中,开发人员不必担心它们。
首先,对于a
...编译器不会推断元组类型,并且它也倾向于将字符串文字扩大到string
键入除某些情况 https://github.com/Microsoft/TypeScript/pull/10676。让我们引入一个名为的辅助函数stringTuple()
:
function stringTuple<T extends string[]>(...args: T) { return args; }
这推断出一个来自剩余参数的元组类型 https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#tuples-in-rest-parameters-and-spread-expressions。现在我们可以用它来制作a
无需输入多余的字符串值:
const a = stringTuple("ONE", "TWO", "THREE");
接下来,让我们介绍一个函数,它接受字符串列表并返回一个对象,该对象的键是这些字符串,并且其值与字符串匹配:
function keyArrayToSameValueAsKeys<T extends string[]>(keys: T): SameValueAsKeys<T>;
function keyArrayToSameValueAsKeys(keys: string[]): { [k: string]: string } {
return keys.reduce((acc, type) => ({ ...acc, [type]: type }), {});
}
在这里,我们使用与您相同的代码reduce
,但我们将它隐藏在它自己的函数中并使用单个重载调用签名 https://www.typescriptlang.org/docs/handbook/functions.html#overloads来表示预期的输出类型。现在,我们可以得到b
像这样:
const b = keyArrayToSameValueAsKeys(a);
b.ONE; // property type is "ONE"
b.TWO; // property type is "TWO"
b.THREE; // property type is "THREE"
如果你把stringTuple()
and keyArrayToSameValueAsKeys()
在库中,用户可以毫不费力地使用它们:
const otherObject = keyArrayToSameValueAsKeys(stringTuple("x", "y", "z"));
// const otherObject: {X: "X", Y: "Y", Z: "Z"}
或者你可以像这样将它们合并在一起:
function keysToSameValueAsKeys<T extends string[]>(...keys: T): { [K in T[number]]: K };
function keysToSameValueAsKeys(keys: string[]): { [k: string]: string } {
return keys.reduce((acc, type) => ({ ...acc, [type]: type }), {});
}
然后通过一次调用获取输出,如下所示:
const lastOne = keysToSameValueAsKeys("tic", "tac", "toe");
// const lastOne: {tic: "tic", tac: "tac", toe: "toe"};
好的,希望对您有所帮助。祝你好运!