【发布时间】:2018-11-17 23:06:10
【问题描述】:
A-构造方法案例
当我想从构造方法参数推断泛型类类型时:
interface ObjectAsMap { [key: string]: boolean }
interface MyClass<T extends ObjectAsMap> {
data: T
constructor(data: T): MyClass<T>
}
class MyClass<T extends ObjectAsMap> {
constructor(data: T) {
this.data = data
}
}
const a = new MyClass('Wrong parameter type')
const b = new MyClass({
first: true,
second: false,
})
console.log(b.data.first)
console.log(b.data.wrongProperty)
不出所料,我得到了2 errors:
-
new MyClass('Wrong parameter type')触发Argument of type '"Wrong parameter type"' is not assignable to parameter of type 'ObjectAsMap'. -
b.data.wrongProperty触发Property 'wrongProperty' does not exist on type '{ first: true; second: false; }'.
B- 非构造方法案例
现在,如果我想从非构造方法触发完全相同的预期行为:
interface ObjectAsMap { [key: string]: boolean }
interface MyClass<T extends ObjectAsMap> {
data: T
declare(data: T): MyClass<T>
}
class MyClass<T extends ObjectAsMap> {
public data: T
public declare(data: T) {
this.data = data
return this
}
}
const myClassInstance = new MyClass()
const a = myClassInstance.declare('Wrong parameter type')
const b = myClassInstance.declare({
first: true,
second: false,
})
console.log(b.data.first)
console.log(b.data.wrongProperty)
我只得到the first error:
-
myClassInstance.declare('Wrong parameter type')触发Argument of type '"Wrong parameter type"' is not assignable to parameter of type 'ObjectAsMap'.。
b.data.wrongProperty 也应该触发错误,因为b#data 中不存在此属性。当我将鼠标悬停在b.data 上方时,它告诉我(property) MyClass<ObjectAsMap>.data: ObjectAsMap 而不是(property) MyClass<{ first: true; second: false; }>.data: { first: true; second: false; }。
问题
有没有办法像我在案例 A 中那样推断案例 B 中的参数类型?
【问题讨论】:
标签: typescript