Below is an example of TypeScript generics that I found on typescriptlang.
function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) {
return obj[key];
}
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a");
getProperty(x, "m");
I wanted to extract the generic type to a variable for reuse. However, my attempt resulted in an error:
type MyType<Type, Key extends keyof Type> = {obj: Type, key: Key}
let x = { a: 1, b: 2, c: 3, d: 4 };
function getPropertyGeneric(params: MyType<x>) {
return obj[key];
}
The error message reads:
Generic type 'MyType' requires 2 type argument(s).
Playground