CodeBlanks Logo Icon CodeBlanks

What is an interface?

Learn to define object shapes with Interface.

What is an interface?

An interface defines the shape of an object: which properties it has and their types. It acts as a contract that objects must follow. It is defined with the interface keyword.

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

An interface checks object structure at compile time.

An interface is a contract

When you use an interface as a type, the object must match the interface exactly. Missing or extra properties cause compile errors. This creates a contract between different parts of the code.

interface Kisi {
  ad: string;
  yas: number;
}
let kisi: Kisi = {
  ad: "Ali",
  yas: 25
};  // valid

An interface guarantees the object follows the contract.

Practice Define and use an interface

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

Starter code

index.ts
// Kisi adında bir interface tanımla
// ad (string) ve yas (number) özellikleri içersin
// kisi değişkenini Kisi türünde tanımla, değer: { ad: "Ayşe", yas: 28 }
// kisi.ad değerini yazdır

Sample solution

index.ts
interface Kisi {
    ad: string;
    yas: number;
}
let kisi: Kisi = { 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 an interface define?

  • A variable's value
  • An array's length
  • The shape of an object Correct answer
  • A function's return type

Explanation: An interface specifies an object's shape by defining property names and types; it is a contract that objects must follow.

2 Complete the interface property

Question
interface Nokta {
  x: number;
  y: ____;
}
Answer
interface Nokta {
  x: number;
  y: number;
}

Explanation: A point's <code>y</code> coordinate is a number; <code>number</code> is the correct type. <code>string</code> and <code>boolean</code> are wrong for a coordinate, and <code>void</code> is not a property type.

3 Interface concepts

Term Meaning
interface Kisi { ... } Object shape definition
interface Contract definition
let k: Kisi = { ... } Using interface as a type
Interface Specifying object structure

All lessons in Beginner