目录
1、类型别名
type Point ={
x:number,
y:string
}
function show(pt:Point){
console.log(pt.x);
console.log(pt.y);
}
show({x:66,y:"name"})
2、接口
interface Point ={
x:number,
y:string
}
function show(pt:Point){
console.log(pt.x);
console.log(pt.y);
}
show({x:66,y:"name"})
区别在于:
类型别名本身无法添加新的属性,而接口是可以扩展的
类型别名通过交集扩展类型,已经存在的接口不可改变
interface通过继承扩展类型,已经存在的接口可添加新字段
// Interface
// 通过继承扩展类型
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
const bear = getBear()
bear.name
bear.honey
// Type
// 通过交集扩展类型
type Animal = {
name: string
}
type Bear = Animal & {
honey: boolean
}
const bear = getBear();
bear.name;
bear.honey;
// Interface
// 对一个已经存在的接口添加新的字段
interface Window {
title: string
}
interface Window {
ts: TypeScriptAPI
}
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
// Type
// 创建后不能被改变
type Window = {
title: string
}
type Window = {
ts: TypeScriptAPI
}
// Error: Duplicate identifier 'Window'.
3、类型断言
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
或者
const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");
或者:双重断言
const a = (expr as any) as T;
4、非空断言操作符(!)
TypeScript 提供了一个特殊的语法,可以在不做任何检查的情况下,从类型中移除 null
和 undefined
,这就是在任意表达式后面写上 !
,这是一个有效的类型断言,表示它的值不可能是 null
或者 undefined
:
function liveDangerously(x?: number | null) {
// No error
console.log(x!.toFixed());
}
只有当你明确的知道这个值不可能是 null
或者 undefined
时才使用 !
。
5、!!相当于Boolean()
Boolean():0
、NaN
、""
、0n
、null
undefined
这些值都会被转为 false