Susitha Ravinda Senarath
Susitha Ravinda Senarath

Reputation: 1678

Extract function interface with generics to a separate type/interface variable

Following is a typescript generic example I got from 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");

Is it possible to extract the generic type to a type variable in order to reuse it? Tried following but it gives 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];
}

error is

Generic type 'MyType' requires 2 type argument(s).

Playground

Upvotes: 0

Views: 120

Answers (1)

aleksxor
aleksxor

Reputation: 8340

For the type defined as:

type MyType<Type, Key extends keyof Type> = {obj: Type, key: Key}

you have to provide explicitly 2 type parameters:

function getPropertyGeneric(params: MyType<typeof x, keyof typeof x>) {
  return params.obj[params.key];
}

playground link

But you may use generic parameter default for the second type parameter. And define MyType as:

type MyType<Type, Key extends keyof Type = keyof Type> = {obj: Type, key: Key}

The you may provide or omit the second type parameter:

function getPropertyGeneric2(params: MyType<typeof x, keyof typeof x>) { // no error
  return params.obj[params.key];
}

function getPropertyGeneric1(params: MyType<typeof x>) { // no error
  return params.obj[params.key];
}

playground link

Also note that you cannot use value x in type position. You have to get it's type with typeof operator.

Upvotes: 3

Related Questions