Deriving Types From Values in TypeScript

When a value is syntactically assigned to a variable it also associates a type with that variable.

const geralt = {
  name: 'Geralt',
  swordsmanshipSkills: 10
}

type Witcher = typeof geralt
// type Witcher = {
//   name: string;
//   swordsmanshipSkills: number;
// }

One of the crucial points to observe is that the types of name and swordsmanshipSkills are not string literal type 'Geralt' and numeric literal 10 respectively but string and numeric. This is because TypeScript assumes that an object's properties can be changed. It is possible to tell TypeScript that the types of properties should be immutable literals using the as const operator.

const geralt = {
  name: 'Geralt',
  swordsmanshipSkills: 10
} as const

type Witcher = typeof geralt
// type Witcher = {
//   readonly name: "Geralt";
//   readonly swordsmanshipSkills: 10;
// }

As presented above a type implicitly assigned to a variable can be extracted using the typeof operator and used as any other type in TypeScript operations.

const geralt = {
  name: 'Geralt',
  swordsmanshipSkills: 10
}

type Witcher = typeof geralt

const eskel: Witcher = {
  name: 'Eskel',
  swordsmanshipSkills: 9
}

In addition to the possibility of extracting types from variables, it is also possible to extract types from properties of variables.

const geralt = {
  name: 'Geralt',
  swordsmanshipSkills: 10
}

type Name = typeof geralt.name
// type Name = string

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.