【发布时间】:2020-05-13 03:00:43
【问题描述】:
class Test {
constructor(public stringprop: string, public numprop: number){}
}
function generic<T, K extends keyof T>(propertyName: K, value: T[K]) {
return `${propertyName} = ${value}`;
}
function instance<T, K extends keyof T>(instance: T, propertyName: K, value: T[K]) {
return `${propertyName} = ${value}`;
}
// OK
generic<Test, keyof Test>("numprop", "das")
// Argument of type '"das"' is not assignable to parameter of type 'number'.
instance(new Test("das", 1), "numprop", "das")
基于此我有两个问题:
- 为什么第一个调用被认为正常,而第二个调用却不行?
- 有没有办法只使用第一个泛型参数 (Test) 并且不传递实例来正确键入它?
【问题讨论】:
标签: typescript