一、type 与 interface 的定义
type Person = {
name: string;
age: number;
sex?: string;
}
interface People {
name: string;
age: number;
sex?: string;
}
function introduction (person: Person | People) {
console.log('我名字叫' + person.name);
console.log('我今年' + person.age);
person.sex ? console.log('是个' + person?.sex + '人') : null;
}
introduction({name: '毛叔叔', age: 18});
// '我名字叫毛叔叔'
// '我今年18'
二、type 与 interface 的定义扩展
type PersonName = {
name: string;
}
type PersonAge = {
age: number;
}
type Person = PersonName & PersonAge & {
sex?: string;
}
// type Person = {
// name: string;
// age: number;
// sex?: string;
// }
interface PeopleName {
name: string;
}
interface PeopleAge {
age: number;
}
interface People extends PeopleName, PeopleAge {
sex?: string;
}
// interface People {
// name: string;
// age: number;
// sex?: string;
// }
function introduction (person: Person | People) {
console.log('我名字叫' + person.name);
console.log('我今年' + person.age);
person.sex ? console.log('是个' + person?.sex + '人') : null;
}
introduction({name: '毛叔叔', age: 18, sex: '男'});
// '我名字叫毛叔叔'
// '我今年18'
// '是个男人'
三、type 与 interface 的不同之处
type Person = {
name: string;
}
type Person = {
age: number;
}
// Duplicate identifier 'Person'.(重复标识符“人员”)
// 不能重复定义 type
interface People {
name: string;
}
interface People {
age: number;
}
// interface People {
// name: string;
// age: number;
// }
// 重复定义 interface 会默认将其扩展在一起
function a (p: People) {
console.log(p.name, p.age)
}
a({ name: '毛叔叔', age: 18 })