Typescript add only some type parameters
I would like to do this:
function foo<A, K extends keyof A>(a: A, key: K): A[K] {
return a[key];
}
foo<Type>({ key: 'value' }, 'key');
But this doesn't work because ts requires all or none of generic types to be explicitly typed.
My workaround:
function bar<A>() {
return {
foo<K extends keyof A>(a: A, key: K): A[K] {
return a[key];
},
};
}
bar<Type>().foo({ key: 'value' }, 'key');
Here the K
type is implicit.
Now my question is, have any of you had the same problem and how did you solve it?
https://github.com/microsoft/TypeScript/issues/26242
I found this proposal on github which would make type parameters optional if possible. This has been open for a while though, in the mean time I'd still like to know your workarounds.
In fact, you don't need to write Type
, typescript will try to infer the type of A
, like
function foo<A, K extends keyof A>(a: A, key: K): A[K] {
return a[key];
}
foo( { key: "value" }, "key" );
interface Bar {
name: string;
age: number;
address: string;
}
const bar: Bar = {
name: "tim",
age: 18,
address: ""
};
// It can also get the correct type
foo( bar, "name" );
TS playground