当前位置:网站首页>typescript type 和 interface 的区别
typescript type 和 interface 的区别
2022-08-04 03:04:00 【alokka】
1. interface侧重于描述数据结构,type侧重于描述类型
interface A{
name:string; }
type B = 'bb'|'cc'
2. 都可以描述一个对象或者函数
interface user {
name: string;
age: number
}
interface setUser {
(name: string, age: number): void
}
type hoster = {
name: string;
age: number;
}
type setHoster = (name: string, age: number) => void
3. interface 可以定义相同的类型名称,多个相同类型名称会合并,type 不可以
interface Window {
title: string
}
interface Window {
ts: TypeScriptAPI
}
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {
});
type Window = {
title: string
}
type Window = {
ts: TypeScriptAPI
}
// Error: Duplicate identifier 'Window'.
4. interface 可以继承, type不可以
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
const bear = getBear()
bear.name
bear.honey
type Animal = {
name: string
}
type Bear = Animal & {
honey: boolean
}
const bear = getBear();
bear.name;
bear.honey;
5. type专属功能
// type专属 联合类型
interface Dog {
wang()
}
interface Cat {
miao()
}
type Pet = Dog | Cat
type PetList = [Dog,Cat]
边栏推荐
猜你喜欢
【观察】超聚变:首提“算网九阶”评估模型,共建开放繁荣的算力网络
Countdown to 2 days, the "New Infrastructure of Cultural Digital Strategy and Ecological Construction of Cultural Art Chain" will kick off soon
docker+网桥+redis主从+哨兵模式
sqoop ETL工具
STM8S105K4T6------Serial port sending and receiving
sqoop ETL tool
STM8S105K4T6------串口发送和接收
mpf5_定价Bond_yield curve_Spot coupon_duration_有效利率_连续复利_远期_Vasicek短期_CIR模型Derivatives_Tridiagonal_ppf
tkmapper的crud示例:
new Date将字符串转化成日期格式 兼容IE,ie8如何通过new Date将字符串转化成日期格式,js中如何进行字符串替换, replace() 方法详解
随机推荐
keytool命令
如果禁用了安全启动,GNOME 就会发出警告
董明珠直播时冷脸离场,员工频犯低级错误,自家产品没人能弄明白
QNX Hypervisor 2.2用户手册]10.2 vdev 8259
DHCP服务详解
哎,又跟HR在小群吵了一架!
基于Qt的目录统计QDirStat
P3384 【模板】轻重链剖分/树链剖分
如何在MySQL中的数据库下删除所有的表
Day13 Postman的使用
WPE详细教程
Countdown to 2 days, the "New Infrastructure of Cultural Digital Strategy and Ecological Construction of Cultural Art Chain" will kick off soon
【指针内功修炼】深度剖析指针笔试题(三)
逻辑漏洞----其他类型
How many ways do you know about communication between multiple threads?
STM8S105k4t6c--------------点亮LED
系统太多,多账号互通如何实现?
【观察】超聚变:首提“算网九阶”评估模型,共建开放繁荣的算力网络
织梦响应式酒店民宿住宿类网站织梦模板(自适应手机端)
ingress 待完善