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

时间:2020-06-21 07:29:50

标签: typescript typescript-generics

我有一个带有某些参数类型的函数:

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

我有一个熟悉的通用类型的界面,如下所示:

interface SomeInterface<T> {
    field1: string;
}

现在我想推断接口的通用参数并将其分配给函数的返回类型:

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

const res1 = func(value1);

我需要 res1 的类型是数字

我需要使用什么功能签名?

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

1 个答案:

答案 0 :(得分:1)

如果没有任何属性引用该类型,则在接口中使用通用类型毫无意义。

这是一个接收通用类型并将其应用于其属性之一的接口:

interface SomeInterface<T> {
    field1: T;
}

另一方面,如果要创建具有通用返回类型的函数:

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

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

最后,如果您希望函数将泛型作为参数接收并返回另一个泛型:

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

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