Basic syntax
We know that we can use object literals to specify what property types we can use. However, what if you have multiple objects with the same structure? Interface is a programming structure that allows to create types for objects.
interface Settings {
color: string;
delay: number;
retry: boolean;
}
const mySettings: Settings = {
color: "black",
delay: 1000,
retry: false
}
console.log(mySettings.color);
Enter fullscreen mode Exit fullscreen mode
Pay attention that when we define interface we use “semicolon”.
Optional property
We can define optional property using ?: symbols:
interface Settings {
color: string;
delay: number;
retry?: boolean;
}
const mySettings: Settings = {
color: "black",
delay: 1000
}
console.log(mySettings.retry); //undefined
Enter fullscreen mode Exit fullscreen mode
Index signatures
Sometimes we don’t know how many properties an object will have. We can specify expected types:
interface Person {
[key: string]: string;
}
const p: Person = {
name: 'Mary',
lastName: 'Smith'
}
p['age'] = 50; // Type 'number' is not assignable to type 'string'
Enter fullscreen mode Exit fullscreen mode
Methods
Of course, we should be able to define methods:
interface Settings {
color: string;
delay: number;
describe: () => void;
}
const mySettings: Settings = {
color: "black",
delay: 1000,
describe: function () {
console.log("Your favorite color is " + this.color)
}
}
console.log(mySettings.describe());
Enter fullscreen mode Exit fullscreen mode
Here, in interface, we defined type of
describeas() => void, that means function. In this casevoiddoesn’t indicate that a function mustn’t return any value, it indicates that it can return any value. The other way to set function type is :describe(): void.
Inheritance
Interfaces can inherit properties from another ones using extends:
interface Settings {
color: string;
delay: number;
describe: () => void;
}
interface Game extends Settings{
character: string;
}
const myGame: Game = {
color: "black",
delay: 1000,
describe: function () {
console.log("Your favorite color is " + this.color);
return 'hi';
},
character: 'goat'
}
console.log(myGame.character); // goat
Enter fullscreen mode Exit fullscreen mode
Using as argument in function
interface Settings {
color: string;
delay: number;
}
function changeSettings(s: Settings): Settings {
return {
color: s.color,
delay: s.delay + 1000
}
}
Enter fullscreen mode Exit fullscreen mode
We specify what we expect the argument to be.
답글 남기기