DEV Community

Santiago Salazar Pavajeau
Santiago Salazar Pavajeau

Posted on

TypeScript interfaces

Interfaces in typescript are a way to define the data types (string, number, boolean, etc.) of the properties in an object, arguments of functions or classes, or values of arrays or tuples.

An object with an interface

To initialize an object that has its properties controlled by exclusively by the data types we need, we can create an interface and set the initialized object type let person: PersonConfig = ... to the interface.

interface UserConfig{
    name: string;
    age: number;
    programmer: boolean;
}

let user: UserConfig = {
    name: "Santiago",
    age: 30,
    programmer: true
}
Enter fullscreen mode Exit fullscreen mode

Changing age: 30 to age: '30' will throw the error: 'string' is not assignable to a 'number'.

A function with an interface

We can create an interface that controls the arguments of the function and the return value.


interface UserConfig{
    name: string;
    age: number;
    programmer: boolean;
}

interface NewUserConfig{
 (name: string; age: number; programmer: boolean;) : UserConfig
} 
const createUser : NewUserConfig = (n: string; a: number; p: boolean;) : UserConfig => {
 const user: UserConfig = {name: n, age: a, programmer: p} 
 return user
} 

Enter fullscreen mode Exit fullscreen mode

We make sure to return an object user that has the type UserConfig we defined in the previous code snippet. But also we restrict the data types of the arguments passed into the functions. The type of the function is NewUserConfig, while its return type is UserConfig and its argument types are: name: string; age: number; programmer: boolean;.

Feel more than welcome to reach out with comments/ideas on LinkedIn or Twitter

Resources: TypeScript Handbook: Interfaces

Top comments (0)