简体   繁体   English

如何推断 TypeScript 中泛型的子类型?

[英]How to infer subtype of generic in TypeScript?

I have a function with some argument's type:我有一个带有一些参数类型的 function:

function func<T extends {field1: string}>(arg1: T) {
 // function's code
}

I have a familiar interface with generic type, like this:我有一个熟悉的泛型接口,如下所示:

interface SomeInterface<T> {
    field1: string;
}

Now i want to infer generic parameter of interface and assign it to function's return type:现在我想推断接口的通用参数并将其分配给函数的返回类型:

const value1: SomeInterface<number> = {field1: "Hello"};

const res1 = func(value1);

I need a type for res1 is number .我需要res1的类型是number

What a function's signature i need to use?我需要使用什么函数签名?

function func<T extends {field1: string}>(arg1: T) : T extends ???? { // What?

There is no point in using a generic type in an interface if the type is not being referenced by any attribute.如果类型没有被任何属性引用,那么在接口中使用泛型类型是没有意义的。

Here is an interface which receives a generic type and applies that type to one of its attributes:这是一个接收泛型类型并将该类型应用于其属性之一的接口:

interface SomeInterface<T> {
    field1: T;
}

In other hand, if you want to create function with a generic return type:另一方面,如果要创建具有通用返回类型的 function:

function func<T>(): T {
 // code
}

// function call
const res1 = func<number>();

And finally, if you want your function to receive as argument a generic type and return another generic type:最后,如果您希望您的 function 接收一个泛型类型作为参数并返回另一个泛型类型:

function func<T, R>(arg: T) : R {
 // code
}

// function call
const res1 = func<SomeInterface, number>(value1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM