我希望能夠構造一個接受另一個物件的型別并根據該物件中的某些屬性回傳不同型別的型別。這將更容易在代碼中解釋:
// these describe the type of inputs a UI would display
// and their returned values
// e.g. a colorHex UI control should return a string
type Inputs = {
colorHex: string
yearPicker: number
}
// colorHex | yearPicker
type InputTypes = keyof Inputs
// Describes an input. It has a type to define the UI and a label
type Input = {
type: InputTypes
label: string
}
// Describes a composition of inputs. Has an ID and an object with Inputs
type Composition = {
id: string
inputs: Record<string, Input>
}
// Describes a map of compositions
type Compositions = Record<string, Composition>
const comps: Compositions = {
short: {
id: 'short',
inputs: {
bgColor: {
type: 'colorHex',
label: 'BG Color',
},
year: {
type: 'yearPicker',
label: 'Count',
},
},
},
}
// I want to recieve a composition and return a map of input key and the resulting input value type
type InputProps<T extends Composition> = {
[P in keyof T['inputs']]: Inputs[T['inputs'][P]['type']]
}
// The input prop types for comps.short
type ShortProps = InputProps<typeof comps.short>
// What I want ShortProps to equal
type Expected = {
bgColor: string
year: number
}
// ultimately what I want to do with this
const someFn = (props: ShortProps) => {
// props === { bgColor: string; year: number }
}
// this is correct
someFn({ bgColor: '#000', year: 2020 })
// this is incorrect and should result in a type error
someFn({ bgColor: 0, year: '2020' })
這是一個游樂場鏈接。請注意,最后一行在應該給出型別錯誤的時候并沒有給出。
uj5u.com熱心網友回復:
您只需要確保comps滿足(或“匹配”)型別Compositions。在此之前,您通過顯式注釋物件來覆寫物件的型別資訊Compositions。目前在 TS 4.8 中,我們必須為此使用輔助函式:
function comp<C extends Compositions>(c: C) { return c }
const comps = comp({
short: {
id: 'short',
inputs: {
bgColor: {
type: 'colorHex',
label: 'BG Color',
},
year: {
type: 'yearPicker',
label: 'Count',
},
},
},
});
但是,在 4.9 中,我們可以使用satisfies關鍵字:
const comps = {
short: {
id: 'short',
inputs: {
bgColor: {
type: 'colorHex',
label: 'BG Color',
},
year: {
type: 'yearPicker',
label: 'Count',
},
},
},
} satisfies Compositions;
現在,您將根據需要在最后一行收到錯誤。
游樂場 (4.8-)
游樂場 (4.9 )
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/522078.html
標籤:打字稿打字稿泛型
