簡體   English   中英

Typescript - 從聯合或數組派生對象類型

[英]Typescript - derive object type from union or array

我有一個函數,它接受一個字符串數組並返回一個使用該數組中的字符串作為鍵的對象,如下所示:

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

現在我希望打字稿根據函數參數中的數組動態設置返回對象的類型。 我知道我可以通過將它作為元組傳遞來獲得聯合類型的數組值,但不知道如何從那里獲得。 我想要的甚至可以做嗎?

這是否符合您的期望:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM