Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Creating interfaces

In this lesson, we learn what interfaces are and how to create them.

We'll cover the following

• Understanding an interface
• Creating an interface
• Optional interface members
• Readonly properties
• Extending interfaces
• Interfaces vs type aliases
• Wrap up

Understanding an interface #
An interface allows a new type to be created with a name and structure. The structure includes all the
properties and methods that the type has without any implementation.

Interfaces don’t exist in JavaScript; they are only used by the TypeScript compiler type checking process.

Creating an interface #
We create an interface with the interface keyword, followed by its name, followed by the properties and
methods that make up the interface in curly brackets:

interface TypeName {
  propertyName: PropertyType;
  methodName: (paramName: ParamType) => MethodReturnType
}

As an exercise, create an interface called ButtonProps that has a text property of type string and an
onClick method that has no parameters and doesn’t return anything. We should be able to use this interface
to create a BuyButton object beneath it. Run the code when you have finished to check that there are no
errors.

TypeScript

1 // TODO - create the ButtonProps type using an interface
2  
3 const BuyButton: ButtonProps = {
4   text: "Buy",
5   onClick: () => console.log("Buy")
6 }

RUN SAVE RESET

Close

Output 3.354s

index.ts(3,18): error TS2304: Cannot find name 'ButtonProps'.

Hide Answer

interface ButtonProps {
  text: string;
  onClick: () => void;
}

Optional interface members #


Interface members can be optional. Can you guess how you define an optional member?

Hide Answer

An optional member is defined by placing a question mark ( ? ) just before its type annotation.

interface TypeName {
  optionalProperty?: PropertyType;
  optionalMethod?: (paramName: ParamType) => MethodReturnType
}

Change the ButtonProps interface that we created earlier so that the onClick method is optional.

Hide Answer

interface ButtonProps {
  text: string;
  onClick?: () => void;
}

Readonly properties #
A property can be readonly by putting a readonly keyword before the property name:

interface TypeName {
  readonly propertyName: PropertyType;
}

Change the ButtonProps interface that we are working on so that the text property is readonly.

Hide Answer

interface ButtonProps {
  readonly text: string;
  onClick?: () => void;
}

What happens if we try to change the text property on the object after its declaration?

const BuyButton: ButtonProps = {
  text: "Buy",
  onClick: () => console.log("Buy")
}
BuyButton.text = "$20";  // is this okay?

Hide Answer

The TypeScript compiler will complain because text can’t be changed after it is initially assigned its
value.

Let’s look at another code example below. Line 9 should generate a type error right? Run the code and find
out.

TypeScript

1 interface Result {
2   readonly name: string;
3   readonly scores: number[];
4 }
5 let billScores: Result = {
6   name: "Bill",
7   scores: [90, 65, 80]
8 }
9 billScores.scores.push(70);

RUN SAVE RESET

Close

Succeeded

No type error is generated. Why do you think this is?

Hide Answer

Putting the readonly keyword before an array or object property name only ensures its reference won’t
change. So, we can mutate the array but we can’t set the scores property to a different array.

In this case we can put an additional readonly modifier before the array type as in the example below:

interface ImmutableResult {
  readonly name: string;
  readonly scores: readonly number[];
}
let tomScores: ImmutableResult = {
  name: "Tom",
  scores: [50, 95, 80]
}
tomScores.scores.push(70);

A type error will be generated on the last line now. Readonly arrays were introduced relatively recently in
TypeScript 3.4.

Extending interfaces #
Interfaces can extend other interfaces so that they inherit all the properties and methods from the interface
being extended. We do this using the extends keyword after the new interface name and before the interface
name that is being extended:

interface InterfaceA extends InterfaceB {
  ...
}

Create a new interface called ColoredButtonProps that extends the ButtonProps interface you created
earlier in this lesson. Then add a color property of type string . We should be able to create the
GreenBuyButton object beneath it.

Don’t forget to copy your ButtonProps code into the code widget below.

After you have done this, run the code to check that no errors are raised.

TypeScript

1 // TODO -  create a ColoredButtonProps interface that extends ButtonProps
2  
3 const GreenBuyButton: ColoredButtonProps = {
4   color: "Green",
5   text: "Buy",
6   onClick: () => console.log("Buy")
7 }

RUN SAVE RESET

Close

Output 4.662s

index.ts(3,23): error TS2304: Cannot find name 'ColoredButtonProps'.


Hide Answer

interface ColoredButtonProps extends ButtonProps {
    color: string;
}

Interfaces vs type aliases #


Interfaces create types like type aliases do, but interfaces seem more powerful. If this is the case, should we
always use interfaces and forget about type aliases?

Historically, the capabilities of type aliases and interfaces were different, but now they are very similar. For
example, type aliases can have optional and read-only properties, just like an interface. You can extend type
aliases by using intersection, which we’ll learn about later in this category of lessons.

So, it is generally personal preference as to which approach to use when creating types. Just be consistent
with which method you use so that the code isn’t confusing.

Wrap up #
Interfaces are a powerful way of creating new TypeScript types that can be used throughout our code. The
ability to extend existing interfaces helps us build objects from small lower-level interfaces.

More information on interfaces can be found in the TypeScript handbook


(https://www.typescriptlang.org/docs/handbook/interfaces.html).

In the next lesson, we will learn how to combine existing types to construct a new type.

Back Next

Creating type aliases Creating union types

Completed

43% completed, meet the criteria and claim your course certi cate!
Buy Certificate

Ask a Question
Report an Issue
(https://discuss.educative.io/tag/creating-interfaces__creating-types__using-typescript-with-react)

You might also like