typescript中interface和type的使用
interface(接口)
声明对象或者函数,通过extends
继承拓展
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| interface IUser { name: string, age: number, sayHi: () => void }
const user: IUser = { name: 'zhangsan', age: 25, sayHi: () => { console.log('hi, i am zhangsan') } } user.sayHi();
interface ISetUser { (name: string, age: number, sayHi: () => void): void; }
const setUser: ISetUser = (name: string, age: number, sayHi: () => void) => { user.name = name; user.age = age; user.sayHi = sayHi; }
setUser('lisi', 30, () => { console.log('hi, i am lisi') }); user.sayHi();
interface IMaleUser extends IUser { gender: string }
let maleUser: IMaleUser = { name: 'lilei', age: 20, gender: '男', sayHi: () => { console.log('hi, i am lilei') } } maleUser.sayHi();
|
type(类型别名)
声明对象或者函数,通过&
来扩展
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| type IUser = { name: string, age: number, sayHi: () => void }
const user: IUser = { name: 'zhangsan', age: 25, sayHi: () => { console.log('hi, i am zhangsan') } } user.sayHi();
type ISetUser = { (name: string, age: number, sayHi: () => void): void; }
const setUser: ISetUser = (name: string, age: number, sayHi: () => void) => { user.name = name; user.age = age; user.sayHi = sayHi; }
setUser('lisi', 30, () => { console.log('hi, i am lisi') }); user.sayHi();
type IMaleUser = IUser & { gender: string }
let maleUser: IMaleUser = { name: 'lilei', age: 20, gender: '男', sayHi: () => { console.log('hi, i am lilei') } } maleUser.sayHi();
|
声明基本类型别名、联合类型、元组等类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| type id = number
type Dog = { name: string } type Cat = { name: number } type Pet = Dog | Cat; let it1: Pet = { name: 'dahuang' } let it2: Pet = { name: 9527 } console.log(it1.name); console.log(it2.name);
type PetList = [Dog, Pet]; let its: PetList = [{ name: 'xiaohuang' }, it1]; console.log(its);
|
总结
相同点:都可以声明对象或者函数,二者都可以交叉互相继承。
不同点:
type
可以声明更多类型,基本类型别名、联合类型、元组等;
interface
可以合并同名声明。