Typescript-从联合或数组派生对象类型

时间:2020-11-12 10:41:29

标签: arrays typescript types tuples

我有一个函数,该函数需要一个字符串数组,并返回一个使用该数组中的字符串作为键的对象,如下所示:

const ob = arrayToObject(['a', 'b', 'c']); // {a: any, b: any, c: any)

现在,我希望打字稿根据函数参数中的数组动态设置返回对象的类型。我知道我可以通过将其作为元组传递来获得数组类型的联合类型,但不知道如何从中获取。我什至想做什么?

1 个答案:

答案 0 :(得分:3)

这符合您的期望吗?

const ob = arrayToObject(['a', 'b', 'c']);


type Convert<T extends ReadonlyArray<string>> = {
    [P in T[number]]: string

}
type Result = Convert<['foo', 'bar']> // {foo: string, bar: string)

function arrayToObject<T extends ReadonlyArray<string>>(args: readonly string[]): Convert<T> {
    return args.reduce((acc, elem) => ({...acc, [elem]: 'hello' }), {} as Convert<T>)
}

更新

// Please keep in mind, array is index based data structure. Index has `number` type

type Arr = readonly [1,2,3,4,5]

// So, You can try to get value by index
type Value1 = Arr[0] // 1
type Value2 = Arr[1] // 2 ... etc

type Value3 = Arr[0|1] // 1|2

// This is how distributive types work
type Value4 = Arr[number] // 5|1|2|3|4

// TS know that array has numbers as indexes, so he replace `number` with allowed // indexes. I'd willing to bet that TS compiler works much more complicated, but // this is how I understand it