typescript泛型函数从参数返回类型



我想要参数的动态返回类型。

type TestType = {
value1: string,
value2: number
}
function testFn1<T extend TestType>(...pick:(keyof T)[]): ??? { }
//testFn<TestType>("value1")  expect {value1: string}
//testFn<TestType>("value1","value2") expect {value1: string, value2:number}

Plz

如何定义函数返回类型?

我在下面试试。

function test3<T, K extends keyof T>(...vars: K[]): Record<K, string | number>

但这次只返回T

对于返回类型,可以使用Pick实用程序类型。

但是,您还需要实际向函数传递一个T。第一,因此函数实际上有一个对象可以从中拾取值,第二,因此编译器可以推断T

这样,这就起作用了:

function test<T, K extends keyof T>(t: T, ...vars: K[]): Pick<T, K> {
// ...
}
const t: TestType = fromSomewhere();
const result = test(t, "value1", "value2");
console.log(result.value1);
console.log(result.value2)
const result2 = test(t, "value1");
console.log(result2.value1);
console.log(result2.value2); // error, as expected

TypeScript没有部分类型推理。如果将TestType显式提供给T,则无法通过参数类型推断其他泛型类型。

一个解决办法是使用咖喱。您可以在第一个函数调用中显式地提供TestType作为泛型类型,而第二个调用则使用参数推断K

function testFn<T extends TestType>() {
return <K extends keyof T>(...pick: K[]): { [Key in K]: T[Key] } => {
return null!
}
}
const result1 = testFn<TestType>()("value1")
const result2 = testFn<TestType>()("value1","value2")

游乐场

最新更新