What does 'Value<T>' stand for in typescript?

Viewed 65

I met some code like

type Value = {
  [name: string]: string;
};

function foo(a: Value) {
  console.log(a);
}

foo({ name: "foo" });  //ok
foo("hello world");    //error

It's easy to see that Value means an object.

Then I met this:

type Value<T> = {
  [K in keyof T]: T[K];
};

function a<T>(a: Value<T>): void {
  console.log(a);
}

a({ name: "ff" });  //ok
a(1);               //ok

So, what does Value<T> mean? Seems quite like a simple <T>, but I don't understand the particular situation to use it.

1 Answers

In your example code, T is a generic type parameter. It might be helpful to think of it kind of like a variable in JavaScript, but it's for a type instead of a runtime value.

TS Playground

type Person<Name extends string> = {
  name: Name;
};

function createPerson <T extends string>(name: T): Person<T> {
  return { name };
}

const nick = createPerson('Nicholas'); // the type of nick is: Person<"Nicholas">
Related