简体   繁体   中英

How to infer subtype of generic in TypeScript?

I have a function with some argument's type:

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 .

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 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 func<T, R>(arg: T) : R {
 // code
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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