CodeBlanks Logo Icon CodeBlanks

Object type

Learn to explicitly write object types.

Object type

An object type describes the shape of an object: which properties it has and what their types are. Property names and types are written inside curly braces.

let kisi: { ad: string; yas: number } = {
  ad: "Ali",
  yas: 25
};

The object type checks the value's structure at compile time.

Object type matching

The object value must match the type exactly: all required properties must be present with the correct types. A missing property or wrong type causes a compile error. Extra properties are also not accepted.

let p: { x: number; y: number } = {
  x: 3,
  y: 4
};  // valid

The object type must match the value's shape exactly.

Practice Define an object with a type annotation

Declare a variable named kisi with type { ad: string; yas: number } and value { ad: "Ayşe", yas: 28 }. Print the value of kisi.ad with console.log.

Starter code

index.ts
// kisi adında bir nesne tanımla
// tür ad ve yas özellikleri içersin (ad dize, yas sayı)
// değer olarak ad "Ayşe", yas 28 kullan
// kisi.ad değerini yazdır

Sample solution

index.ts
let kisi: { ad: string; yas: number } = { ad: "Ayşe", yas: 28 };
console.log(kisi.ad);

Expected output

Ayşe

Questions and answers

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

1 What does <code>{ ad: string; yas: number }</code> describe?

  • An object type with ad (string) and yas (number) properties Correct answer
  • An array with two elements
  • A function with two parameters
  • A tuple of string and number

Explanation: Property names and types inside curly braces describe an object's shape; <code>ad: string; yas: number</code> is an object type with two properties.

2 Complete the object property type

Question
let nokta: { x: number; y: ____ } = { x: 3, y: 4 };
Answer
let nokta: { x: number; y: number } = { x: 3, y: 4 };

Explanation: Since the value is <code>{ x: 3, y: 4 }</code>, the <code>y</code> property is also a number; the correct type is <code>number</code>. <code>string</code> and <code>boolean</code> do not accept a number.

3 Object type concepts

Term Meaning
{ ad: string } ad property of type string
{ x: number; y: number } x and y number properties
Object type Describing an object's shape
{ yas: number } yas property of type number

All lessons in Beginner