当前位置:网站首页>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]
边栏推荐
猜你喜欢
随机推荐
C program compilation and predefined detailed explanation
脚手架内容详解分析
小程序:扫码打开参数解析
STM8S105k4t6c---------------Light up LED
返回字符串中的最大回文数
JVM内存和垃圾回收-07.堆
单片机C语言->的用法,和意思
Asynchronous programming solution Generator generator function, iterator iterator, async/await, Promise
new Date将字符串转化成日期格式 兼容IE,ie8如何通过new Date将字符串转化成日期格式,js中如何进行字符串替换, replace() 方法详解
STM8S项目创建(STVD创建)---使用 COSMIC 创建 C 语言项目
4路双向HDMI综合业务高清视频光端机8路HDMI高清视频光端机
三分建设,七分管理!产品、系统、组织三管齐下节能降耗
Qt中对象树的机制介绍以及底层实现,各种结果分析:(以及自己写容易犯错的点)
基于Qt的目录统计QDirStat
Architecture of the actual combat camp module three operations
docker+网桥+redis主从+哨兵模式
P3384 【模板】轻重链剖分/树链剖分
安装postgis时报找不到“POSTGIS_VERSION”这个函数
Why use Selenium for automated testing
kingbaseES V8R2/R3 表在指定表空间,为何显示为默认表空间?









