Define the structure for an object for type checking.
Interface vs type
Interface is used only for an object but type is not. So using interface makes you clear working with an object.
interface Person { // (*)
name: string;
age: number;
greet: (phrase: string): void;
}
let user1: Person;
user1 = {
name: 'Suyeon'.
age: '25',
greet(phrase: string) {
console.log(phrase + this.name);
}
}
user1.greet('Hey there');
interface Greetable {
name: string;
greet: (phrase: string): void;
}
class Person implements Greetable { // implements Greeatble, Person...
name: string;
age: 25;
constructor(n: string) {
this.name = n;
}
greet(phrase: string) {
console.log(phrase + this.name);
}
}
readonly
to the field if you set it inside interface
.interface Greetable {
readonly name: string; // (*)
greet: (phrase: string): void;
}
interface Named {
readonly name: string;
}
interface Greetable extends Named { // (*) extends Name, Another...
greet: (phrase: string): void;
}
// using type
type AddFunc = (a: number, b: number) => number;
let add: AddFunc;
add = (n1: number, n2: number) => {
return n1 + n2;
}
// using interface
interface AddFunc {
(a: number, b: number): number;
}
let add: AddFunc;
add = (n1: number, n2: number) => {
return n1 + n2;
}
// interface
interface Named {
readonly name: string;
outputName? : string; // (*)
}
// class
interface Named {
readonly name: string;
outputName? : string; // (*)
}
class Person implements Named {
name?: string; // (*)
constructor(n?: string) { // (*) OR set default value. n: string = "something"
if(n) {
this.name = n;
}
}
}