假设我有这样的函数声明:
function foo<T extends {}>(bar: Array<{ key: keyof T, value: any, otherParam: string}>): T[]我有这样的接口:
interface C {
d: string
e: number
}当我像这样调用foo时:
foo<C>([{key: 'd', value: 'myValue', otherParam: 'other'}, {key: 'e', value: 100, otherParam: 'other'}])我想推断出第二个参数value的类型,然后去掉那个糟糕的any。
我该怎么做呢?
谢谢!
发布于 2020-07-21 00:51:22
使用mapped types将T转化为所需的形状。
type Bar<T> = {
[P in keyof T]: { key: P, value: T[P], otherParam: string }
}[keyof T];完整的解决方案:
type Bar<T> = {
[P in keyof T]: { key: P, value: T[P], otherParam: string }
}[keyof T];
declare function foo<T extends object>(bar: Bar<T>[]): T[]
interface C {
d: string
e: number
}
foo<C>([{key: 'd', value: 'string', otherParam: 'other'}, {key: 'e', value: 100, otherParam: 'other'}])https://stackoverflow.com/questions/62998749
复制相似问题