简体   繁体   English

在 typescript 中,如何使用泛型来约束和描述函数的返回值类型?

[英]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.

相关问题 如何用 Typescript 中的泛型值描述索引类型? - How to describe an index type with generic values in Typescript? TypeScript 泛型条件类型作为泛型 function 的返回值 - TypeScript generic conditional type as return value for generic function 如何使用基于泛型类型的条件类型来描述约束? - How to describe constraint using conditional type which is based on generic type? Typescript Function 具有通用返回类型 - Typescript Function with Generic Return Type Typescript中的泛型函数返回类型 - Generic return type of function in Typescript 如何在 TypeScript 中的 function 的返回类型中使用参数的值作为属性名称? - How to use the value of a parameter as a property name in the return type for a function in TypeScript? 推断 typescript 通用包装器 function 返回类型属性值 - Infer typescript generic wrapper function return type property value 如何描述 function 的返回类型,这是通过通用 function 调用的结果 - How to describe return type of function which is result of call passed generic function 如何在 typescript 中同时声明泛型箭头 function 的返回类型为数组和值? - How to declare the return type of a generic arrow function to be an array and value at the same time in typescript? 如何在 TypeScript 中返回泛型 - How to return a generic type in TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM