简体   繁体   中英

Typescript - derive object type from union or array

I have a function that takes an array of strings and returns an object that uses strings from that array as keys, like that:

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

now i want typescript to dynamically set type of the returned object to be based on the array in the function arguments. I know I can get a union type of array values by passing it as tuple, but don't know how to get from there. Is what i want even possible to do?

does this meet your expectations:

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>)
}

UPDATE

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM