[英]In typescript, How to use a generic to constraint and describe return value type of function?
Look the code,I think tom is type of BB extends AA, So it should be work看代码,我认为汤姆是 BB 扩展 AA 的类型,所以它应该可以工作
Code Error: TS2322: Type 'BB' is not assignable to type 'T'代码错误:TS2322:类型“BB”不可分配给类型“T”
interface AA {
name: string
}
interface BB extends AA{
age: number
}
const tom: BB = {
name: 'tom',
age: 20
}
function something<T extends AA>(): T {
return tom
}
How can I use like我怎样才能使用喜欢
something<BB>()
to get a value which extends AA;得到一个扩展 AA 的值; Or
或者
something<CC>()
which CC extends AA哪个 CC 扩展了 AA
Your identify function should look like this:您的标识 function 应如下所示:
interface AA {
name: string
}
interface BB extends AA{
age: number
}
const tom: BB = {
name: 'tom',
age: 20
}
function identity<T extends AA>(arg: T) {
return arg
}
identity(tom)
The problem with you current implementation is that you are using a specific kind of type T
.您当前实现的问题是您使用的是特定类型的
T
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.