CodeBlanks Logo Icon CodeBlanks

typeof operator

Learn the type of a value with typeof.

The typeof operator

The typeof operator infers a value's type and yields it as a type. typeof ayarlar produces the type of the ayarlar variable. You can store it as a type alias and reuse it elsewhere. Unlike JavaScript's runtime typeof, this works at the type level.

const ayarlar = { tema: "koyu", ses: true };
type AyarTip = typeof ayarlar;
// { tema: string; ses: boolean }

Deriving a type from a value

typeof is especially handy for deriving a type from a const object. When the object's shape changes, the type produced by typeof updates automatically. So you obtain the type from an existing value instead of writing the interface by hand.

Practice Derive a type from a value

Assign the object { tema: "koyu", ses: true } to a variable ayarlar. Define type AyarTip as typeof ayarlar. Write function goster(a: AyarTip): void whose body prints tema via console.log(a.tema). Call goster(ayarlar).

Starter code

index.ts
// ayarlar değişkenine { tema: "koyu", ses: true } ata
// AyarTip türünü ayarlar'ın türü olarak tanımla
// goster fonksiyonu AyarTip parametre alsın
// gövdede console.log ile a.tema yazdır
// ayarlar ile çağır

Sample solution

index.ts
const ayarlar = { tema: "koyu", ses: true };
type AyarTip = typeof ayarlar;
function goster(a: AyarTip): void {
  console.log(a.tema);
}
goster(ayarlar);

Expected output

koyu

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is AyarTip the type of in the code below?

index.ts
const ayarlar = { tema: "koyu", ses: true };
type AyarTip = typeof ayarlar;
  • "koyu" | true
  • any
  • { tema: string; ses: boolean } Correct answer
  • string

Explanation: A const object is still mutable, so its properties infer wide types: tema is string, ses is boolean. typeof gives this object's type.

2 Add typeof

Question
const ayarlar = { tema: "koyu", ses: true };
type AyarTip = ____ ayarlar;
Answer
const ayarlar = { tema: "koyu", ses: true };
type AyarTip = typeof ayarlar;

Explanation: To derive a type from a value you use typeof. keyof takes keys from a type; Pick and Required serve other purposes.

3 typeof parts

Term Meaning
typeof ayarlar The type of the ayarlar value
type AyarTip = typeof ayarlar Type alias from a value
const ayarlar = { tema: "koyu" } The source value for typeof
function goster(a: AyarTip) Derived type as parameter

All lessons in Intermediate