TypeScript是否可以从动态对象推断键?

Bro*_*Kee 2 javascript types interface typescript reactjs

我在这里想要实现的是从数组生成的对象的智能感知/自动完成-像Redux的Action Creator一样string[],可以将字符串数组()简化为具有形状的对象{ [string]: string }

例如:

const a = ['ONE', 'TWO', 'THREE'];

const b = a.reduce((acc, type) => ({ ...acc, [type]: type }), {});

console.log(b);
// Output: b = { ONE: 'ONE', TWO: 'TWO', THREE: 'THREE' };
Run Code Online (Sandbox Code Playgroud)

我已经使用以下方法设法使TypeScript对此有所了解。TypeScript知道键是字符串,但不知道它们是什么。

interface ITypesReturnObject { [s: string]: string }
Run Code Online (Sandbox Code Playgroud)

有没有人想出一种方法来通知TypeScript对象上的键等于数组中的字符串?

任何帮助将不胜感激。

jca*_*alz 5

(假设您在下面使用TS3.0或更高版本)

TypeScript支持字符串文字类型元组类型的概念,因此可以使您的值a具有类型 ['ONE', 'TWO', 'THREE'] ['ONE', 'TWO', 'THREE'],如下所示:

const a: ['ONE', 'TWO', 'THREE'] = ['ONE', 'TWO', 'THREE'];
Run Code Online (Sandbox Code Playgroud)

(实现这一目标的一种不太冗长的方法将在以后出现):

然后,您可以b使用映射类型,将预期的类型表示为从键到与键完全匹配的值的映射

type SameValueAsKeys<KS extends string[]> = { [K in KS[number]]: K };
Run Code Online (Sandbox Code Playgroud)

可以这样使用:

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"
Run Code Online (Sandbox Code Playgroud)

通知编译器如何知道b有三个按键,"ONE""TWO",和"THREE",和值是相同的密钥。


因此,TypeScript当然支持这种类型的动态类型。不幸的是,如上所示,使用起来有点繁琐。减少烦人的一种方法是添加一些帮助程序函数,这些函数允许编译器推断适当的类型,或者至少将类型断言隐藏在开发人员无需担心它们的库中。

首先,对于a...,编译器不会推断出元组类型,并且string除了某些情况下,它还倾向于将字符串文字扩展为该类型。让我们介绍一个名为的辅助函数stringTuple()

function stringTuple<T extends string[]>(...args: T) { return args; }
Run Code Online (Sandbox Code Playgroud)

从其余参数推断出元组类型。现在我们可以使用它来制作,a而无需键入多余的字符串值:

const a = stringTuple("ONE", "TWO", "THREE");
Run Code Online (Sandbox Code Playgroud)

接下来,让我们介绍一个函数,该函数获取字符串列表并返回一个对象,该对象的键是那些字符串,并且其值与这些字符串匹配:

function keyArrayToSameValueAsKeys<T extends string[]>(keys: T): SameValueAsKeys<T>;
function keyArrayToSameValueAsKeys(keys: string[]): { [k: string]: string } {
  return keys.reduce((acc, type) => ({ ...acc, [type]: type }), {});
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们使用与您相同的代码reduce,但将其隐藏在自己的函数中,并使用单个重载调用签名来表示预期的输出类型。现在,我们可以b像这样:

const b = keyArrayToSameValueAsKeys(a);
b.ONE; // property type is "ONE"
b.TWO; // property type is "TWO"
b.THREE; // property type is "THREE"
Run Code Online (Sandbox Code Playgroud)

如果你把stringTuple()keyArrayToSameValueAsKeys()在库中,用户可以使用他们没有太多的麻烦:

const otherObject = keyArrayToSameValueAsKeys(stringTuple("x", "y", "z"));
// const otherObject: {X: "X", Y: "Y", Z: "Z"}
Run Code Online (Sandbox Code Playgroud)

或者,您可以将它们合并在一起,如下所示:

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 }), {});
}
Run Code Online (Sandbox Code Playgroud)

然后在一个调用中获得输出,如下所示:

const lastOne = keysToSameValueAsKeys("tic", "tac", "toe");
// const lastOne: {tic: "tic", tac: "tac", toe: "toe"};
Run Code Online (Sandbox Code Playgroud)

好的,希望对您有所帮助。祝好运!