I want dynamic return type from parameters.
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
How can i define function return type?
I try below.
function test3<T, K extends keyof T>(...vars: K[]): Record<K, string | number>
but this return Just T
CodePudding user response:
For the return type, you can use the Pick
utility type.
But what you also need is to actually pass a T
to the function. One, so the function actually has an object to pick values from, and two, so the compiler can infer T
.
With that, this works:
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
CodePudding user response:
TypeScript does not have partial type inference. If you provide TestType
explicitly to T
, it can not infer other generic types via argument types.
One work-around would be to use currying. You can explicitly provide TestType
as the generic type in the first function call while the second call infers K
with the arguments.
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")