[英]Typescript: Generic class type inference
以下步骤似乎很简单,但是我不确定是什么导致了错误。 我已经寻找了很长时间,但似乎找不到答案。
class MyClass<T > {
property: T = 5 // Error Here: Type '5' is not assignable to type T
}
const tester = new MyClass<number>() // OK
const numberValue: number = tester.property // OK
const stringValue: string = tester.property // Error as expected
我认为T可以从“属性”中推断为数字。 我觉得过去曾经工作过,但不确定。
更新资料
这些定义也有相同的错误。
class MyClass<T extends number> {
property: T = 5 // Error Here: Type '5' is not assignable to type T
}
class MyClass<T extends object> {
property: T = {} // Error Here: Type '{}' is not assignable to type T
}
这应该是行不通的。 无论您在泛型类或方法的定义中编写的内容如何,对于所有可能使用该类或方法的T
值都必须有效。 如果有人执行new MyClass<string>()
使得T
为string
,则分配property: T = 5
无效。 仅当您使用通用类或方法时才进行推断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.