我有以下打字稿代碼:
const a = [{ foo: 1 }, { bar: '2' }]
我希望用來a創建形式的物件:
const b = {
foo: 1,
bar: '2'
}
的型別b應該等同于型別:
type EquivalentType = {
foo: number
bar: string
}
這可能沒有鑄造嗎?如何才能做到這一點?
uj5u.com熱心網友回復:
當然有。這個解決方案不需要as const像@Vija02 那樣的(盡管如果它確實很好)。
映射陣列中所有可能的鍵,然后使用以下方法僅獲取該鍵的型別Extract:
type CreateFrom<T extends ReadonlyArray<unknown>> = { [K in keyof T[number]]-?: Extract<T[number], { [_ in K]: any }>[K] };
然后你只需在假定的函式中使用這種型別:
function createFrom<T extends ReadonlyArray<unknown>>(list: T): CreateFrom<T> {
// ... for you to implement!
}
請注意,您可能需要轉換回傳型別。我認為 TypeScript 不會對此感到太滿意。
最后,這是一個展示解決方案的游樂場。
uj5u.com熱心網友回復:
// You might be able to simplify this
type TypeFromLiteral<T> = T extends string ? string : T extends number ? number : T extends boolean ? boolean : never;
// The "as const" part is important so that we can process the types
const a = [{ foo: 1 }, { bar: '2' }] as const;
// Get the final type
type ObjectUnion = typeof a[number];
type NewType = { [T in ObjectUnion as keyof T]: TypeFromLiteral<T[keyof T]> };
// By itself, this will get the correct value. However, we need to process the type separately and cast it to get what you want.
const b = Object.assign({}, ...a) as NewType;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481032.html
上一篇:目前正在學習苗條,需要一些幫助
