TypeScript Type Aliases vs Interfaces All In One
TypeScript Type Aliases vs Interfaces All In One
Differences Between Type Aliases and Interfaces
Type aliases and interfaces are very similar, and in many cases you can choose between them freely.
Almost all features of an interface are available in type, the key distinction is that a type cannot be re-opened
to add new properties vs an interface which is always extendable.
类型别名和接口非常相似,在很多情况下您可以在它们之间自由选择。
接口的几乎所有功能都可以在类型中使用,关键区别在于不能重新打开
类型以添加新属性,而接口始终是可扩展的。
- 静态扩展
// Extending an interface
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
const bear = getBear()
bear.name
bear.honey
// Extending a type via intersections
type Animal = {
name: string
}
type Bear = Animal & {
honey: boolean
}
const bear = getBear();
bear.name;
bear.honey;
- 动态扩展
定义多个同名的接口,接口的属性会自动合并 ✅
// Adding new fields to an existing interface
interface Window {
title: string
}
interface Window {
// ts: TypeScriptAPI
ts: PromiseConstructor
}
// const src = 'const a = "Hello World"';
// window.ts.transpileModule(src, {});
window.ts
window.title
不可再次定义同名的 Type, 会重复定义冲突报错 ❌
// A type cannot be changed after being created
type Window = {
title: string
}
type Window = {
ts: TypeScriptAPI
}
// Error: Duplicate identifier 'Window'. ❌
- 限制
Interfaces may only be used to declare the shapes of objects
, not rename primitives
.
接口只能用于声明对象
的形状,不能重命名基元
。
// object ✅
interface PersonInterface {
name: string
age: number
}
const pi: PersonInterface = {
name: 'pi',
age: 18,
}
// object ✅
type PersontType = {
name: string
age: number
}
const pt: PersontType = {
name: 'pt',
age: 22,
}
// primitive value ❌
// interface PrimitiveInterface = string;
interface PrimitiveInterface {
[key: string]: string
}
// const primitiveI: PrimitiveInterface = 'primitive value';
// Type 'string' is not assignable to type 'PrimitiveInterface'.(2322) ❌
/*
const primitiveI: {
// [key in keyof PrimitiveInterface]
// [key: string in keyof PrimitiveInterface]
} = 'primitive value';
*/
const primitiveI: keyof {[key: string]: PrimitiveInterface} = 'primitive value';
// const primitiveI: string | number ⚠️
// primitive value ✅
type PrimitiveType = string;
const primitiveT: PrimitiveType = 'primitive value';
// const primitiveT: string ✅
refs
https://www.typescriptlang.org/cheatsheets
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16378111.html
未经授权禁止转载,违者必究!