typescript interface or type code example
Example 1: typescript interface function
interface IEmployee {
empCode: number;
empName: string;
getSalary: (number) => number;
getManagerName(number): string;
}
Example 2: typescript class interface
interface IPerson {
name: string
age: number
hobby?: string[]
}
class Person implements IPerson {
name: string
age: number
hobby?: string[]
constructor(name: string, age: number, hobby: string[]) {
this.name = name
this.age = age
this.hobby = hobby
}
}
const output = new Person('john doe', 23, ['swimming', 'traveling', 'badminton'])
console.log(output)
Example 3: typescript type vs interface
type Weekday = 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday' | 'Saturday' | 'Sunday';
let day1: Weekday = 'Monday';
let day2: Weekday = 'January';
interface Person {
firstName: string;
lastName: string;
age: number;
}
let person1: Person = {
firstName: 'James',
lastName: 'Smith',
age: 30
}
let person2: Person = {
firstName: 'Mary',
lastName: 'Williams'
}
Example 4: typescript type interface
interface Animal { type Animal = {
name: string; name: string;
} }
interface Bear extends Animal { type Bear = Animal & {
honey: boolean; honey: Boolean;
} }
const bear = getBear(); const bear = getBear();
bear.name; bear.name;
bear.honey; bear.honey;