31
loading...
This website collects cookies to deliver better user experience
interface
keyword. This keyword is followed by the name of the interface add curly brackets. These brackets contain the shape of an object, its properties and types. You specify these properties and types as key:value pairs.// Create an empty interface:
interface EmptyObject {}
// Create interface Cat:
interface Cat {
name: string;
age: number;
hairColor: string;
weight: number;
height: number;
}
// Create interface Car:
interface Car {
model: string;
manufacturer: string;
numberOfWheels: number;
type: string;
}
// Create interface User:
interface User {
username: string;
password: string;
email: string;
isActive: boolean;
role: 'admin' | 'user' | 'guest';
}
Cat
interface defines an object that has five properties: name
, age
, hairColor
, weight
and height
. All these properties are required. Values of name
and hairColor
must be strings. The rest must be numbers. The Car
interface defines an object that has four properties: model
, manufacturer
, numberOfWheels
and type
.numberOfWheels
must be a number. The rest must be strings. Lastly, the User
interface defines an object that has again five properties: username
, password
, email
, isActive
and role
. Values of the first three must be strings.isActive
property must be a boolean, either true or false. The value of role
is more concrete. It says that the value must be one of these three strings: 'admin'
, 'user'
or 'guest'
. If you use any other string, TypeScript will warn you that the value you use is wrong, even though the type is the same.// Create an interface User:
interface User {
password: string;
email: string;
role: 'admin' | 'user' | 'guest';
logUserData: () => string;
}
// Use interface to annotate an object:
const userJoe: User = {
password: 'some_secret_password123645',
email: '[email protected]',
role: 'user',
logUserData: () => `${email}, ${role}`
}
// Create an interface User:
interface User {
password: string;
email: string;
role: 'admin' | 'user' | 'guest';
logUserData: () => string;
}
// Create a function with "user" parameter
// and annotate the "user" parameter with "User" interface.
function getUserEmail(user: User) {
return user.email
}
implements
keyword. This will tell TypeScript that a given class should use an interface that follows after this keyword.// Create interface Person:
interface Person {
// Define some class properties
// of type string and number:
firstName: string;
lastName: string;
age: number;
gender: 'male' | 'female';
// Define class method that returns a string:
sayHello: () => string;
}
// Annotate class "Female" with "Person" interface:
class Female implements Person {
// Define required public properties:
firstName: string
lastName: string
age: number
gender: 'male' | 'female'
// Create constructor and assign existing properties:
constructor(firstName: string, lastName: string, age: number, gender: 'male' | 'female') {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.gender = gender
}
// Define required class method:
sayHello() {
return `Hello, my name is ${this.firstName}.`
}
}
?
) between the property name and the colons.// Create an interface with optional properties:
interface Person {
firstName: string;
lastName: string;
middleName?: string; // <= This property will be optional
}
// This will work:
const bill: Person = {
firstName: 'Bill',
lastName: 'Doherty',
middleName: 'Stevens'
}
// This will also work because "middleName"
// property is not required:
const will: Person = {
firstName: 'William',
lastName: 'Connors',
}
// This will not work because "lastName"
// property is required but missing:
const jack: Person = {
firstName: 'Jack',
middleName: 'O\'Conor',
}
// TS error: Property 'lastName' is missing in type '{ firstName: string; middleName: string; }' but required in type 'Person'.
readonly
keyword before the property name. This will tell TypeScript that the property that follows is a read-only property.// Create interface with read-only property:
interface User {
username: string;
password: string;
readonly email: string; // <= This property will be read-only
}
// Annotate object "userFrank" with "User" interface:
const userFrank: User = {
username: 'frankie',
password: '123456782',
email: '[email protected]'
}
// Try to change value of "username" property:
userFrank.username = 'frankman'
// Try to change value of "email" property:
userFrank.email = '[email protected]'
// TS error: Cannot assign to 'email' because it is a read-only property.
// Create interface for multiply function:
interface MultiplyFunc {
// Specify only parameters and return type:
(a: number, b: number): number;
}
// Annotate the "multiply" function
// with "MultiplyFunc" interface:
const multiply: MultiplyFunc = (a, b) => {
return a * b
}
// Note:
// Thanks to MultiplyFunc interface TypeScript
// will know that "a" and "b" in "multiply" function
// are numbers so you don't have to type them explicitly.
interface MyFunc {
// Specify only parameters and return type:
(a: number, b: string, c: boolean): string;
}
// Annotate the "multiply" function
// with "MultiplyFunc" interface:
const myFunc: MyFunc = (a, b, c) => {
return `a is ${a}, b is ${b}, c is ${c}`
}
// TypeScript will correctly infer "a" to be number,
// "b" to be string and "c" to be boolean.
extends
keyword. This keyword allows you to extend one interface with just one interface as well as with multiple.extends
keyword goes between the first interface, the one you are extending, and the second, the one you are extending with.// Create "Person" interface:
interface Person {
name: string;
}
// Create "Male" interface that extends "Person" interface:
interface Male extends Person {
gender: 'Male';
}
// Basically translates to:
// interface Male {
// name: string;
// gender: 'Male';
// }
// Create "Female" interface that also extends "Person" interface:
interface Female extends Person {
gender: 'Female';
}
// Basically translates to:
// interface Female {
// name: string;
// gender: 'Female';
// }
// Create "Boy" interface that extends "Person" and "Male" interfaces:
interface Boy extends Person, Male {
age: number;
}
// Basically translates to:
// interface Boy {
// name: string;
// gender: 'Male';
// age: number;
// }
// Create "Girl" interface that extends "Person" and "Female" interfaces:
interface Girl extends Person, Female {
age: number;
}
// Basically translates to:
// interface Girl {
// name: string;
// gender: 'Female';
// age: number;
// }
const stanley: Person = {
name: 'Stanley'
}
const david: Male = {
name: 'David',
gender: 'Male'
}
const sarah: Female = {
name: 'Sarah',
gender: 'Female'
}
const andreas: Boy = {
name: 'Andreas',
gender: 'Male',
age: 13
}
const victoria: Girl = {
name: 'Victoria',
gender: 'Female',
age: 6
}
<>
) like in the example below.// Create interface for UserData:
interface UserData {
name: string;
email: string;
}
// Create a generic interface:
interface ApiResponse<T> {
date: Date;
code: number;
payload: T[];
}
// Create function to fetch API
async function fetchAPI() {
// Use ApiResponse "interface" and pass
// the "UserData" interface as argument (for T argument):
const data: ApiResponse<UserData> = await fetch('/some_api_endpoint')
// The "ApiResponse<UserData>" basically translates to:
// interface ApiResponse<T> {
// date: Date;
// code: number;
// payload: UserData[];
// Or:
// payload: [name: string; email: string;]
// }
}