Deriving Types From Values
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