Describe the shape of an object

INPUT · Slides

Declaring a shape with interface

01 / 06

The other way of declaring a shape

There are in fact two ways to name the shape of an object. One is the type you just did. The other is interface.

You write interface Name { ... }. Using it is exactly the same as with type — you write the name wherever a type goes.

interface Person {  name: string;  age: number;}const yui: Person = { name: "Yui", age: 20 };console.log(yui);

Result

{ name: "Yui", age: 20 }

02 / 06

Only two visible differences

Compared with type, these are the only differences in how you write it.

  • no = after the name
  • no ; after the closing brace

type puts another name on a shape, so it needs the =. interface declares that a shape exists, so it ends with {}, like a function or a class.

type Person = { name: string };interface Cat {  name: string;}const p: Person = { name: "Yui" };const c: Cat = { name: "Mochi" };console.log(p.name + " and " + c.name);

Result

Yui and Mochi

03 / 06

You use it just like type

Once declared, nothing else changes. It goes on variables, on function parameters, on return types.

What goes inside is the same too — just property names and their types, lined up.

interface Item {  name: string;  price: number;}function tell(i: Item): void {  console.log(i.name + " is " + i.price + " yen");}tell({ name: "pen", price: 120 });

Result

pen is 120 yen

04 / 06

The error when something is missing

The error for a missing property mentions the name you gave, too. It is the same message as with type.

Whichever way you declared it, to TypeScript it is only ever "the shape called Item".

interface Item {  name: string;  price: number;}const i: Item = { name: "apple" };

Result

Type error: Property 'price' is missing in type '{ name: string; }' but required in type 'Item'.

05 / 06

It catches your typos too

Mistype a name while making one and it stops there. It even offers you a suggestion: "did you mean age?"

On a phone the keyboard likes to capitalise the first letter for you, and Age is not age. An error is nothing to worry about. It is only telling you what went wrong, so do what it says.

interface Person {  name: string;  age: number;}const p: Person = { name: "Yui", Age: 20 };

Result

Type error: Object literal may only specify known properties, but 'Age' does not exist in type 'Person'. Did you mean to write 'age'?

06 / 06

So which should you use?

If you are only writing the shape of an object, either is fine. They do very nearly the same things.

Working in a team, the thing that matters more is that you all pick one. This course will keep showing you both, on purpose. Being able to read them is what counts; do not worry about the fine distinctions yet.

Let us write some. For a while in this chapter we will use interface.