[英]Get type of generic's value by key declared on a property in Typescript interface and use it as the type of a function's parameter
I want to add a function signature on a typescript interface which one of its parameters will have a type based on the declared key's value.我想在 typescript 接口上添加 function 签名,其中一个参数将具有基于声明的密钥值的类型。
I've tried the approach bellow but it doesn't work, as the value
's type is every possible type from T
.我尝试了下面的方法,但它不起作用,因为value
的类型是T
中所有可能的类型。 Instead, I want the value of the declared key相反,我想要声明键的值
so if key "num" is a number, I want the "value" parameter in function to be a number所以如果键“num”是一个数字,我希望 function 中的“value”参数是一个数字
type RowType = Record<string, any>
interface Row<T = RowType, K extends keyof T = keyof T> {
key: K
render: (value: T[K], row: T) => any
}
interface DumpRecord = {
arr: string[],
num: number,
str: string
}
let row: Row<DumpRecord> = {
key: 'arr',
render: (value, row) => ... // value should be array, row should be DumpRecord
}
// or
let row: Row<DumpRecord> = {
key: 'num',
render: (value, row) => ... // value should be number
}
You need to use discriminated unions here:您需要在这里使用有区别的联合:
type RowType = Record<string, any>
interface Row<T = RowType, K extends keyof T = keyof T> {
key: K
render: (value: T[K], row: T) => any
}
interface DumpRecord {
arr: string[],
num: number,
str: string
}
type Values<T> = T[keyof T]
type Union = Values<{
[Prop in keyof DumpRecord]: Row<DumpRecord, Prop>
}>
const one: Union = {
key: 'arr',
render: (value, row) => {
value // string[]
}
}
const two: Union = {
key: 'num',
render: (value, row) => {
value // number
}
}
You can find more examples in this question and my article您可以在这个问题和我的文章中找到更多示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.