通过基础类型组合而来的, 我们可以叫他高级类型. 包含: 交叉类型 / 联合类型 / 接口等等, 当然不止他们3个。
接口(interface)
一种定义复杂类型的格式, 比如我们用对象格式存储一篇文章, 那么就可以用接口定义文章的类型:
interface Article {title: stirng;count: number;content:string;fromSite: string;}const article: Article = {title: '为vue3学点typescript(2), 类型',count: 9999,content: 'xxx...',fromSite: 'baidu.com'}
在这种情况下,当我们给article赋值的时候, 如果任何一个字段没有被赋值或者字段对应的数据类型不对, ts都会提示错误, 这样就保证了我们写代码不会出现上述的小错误.
非必填(?)
还是上面的例子, fromSite的意思是文章来自那个网站,如果文章都是原创的, 该字段就不会有值, 但是如果我们不传又会提示错误, 怎么办?
这时候就需要标记fromSite字段为非必填, 用”?”标记:
interface Article {title: stirng;count: number;content:string;fromSite?: string; // 非必填}// 不会报错const article: Article = {title: '为vue3学点typescript(2), 类型',count: 9999,content: 'xxx...',}
用接口定义函数
接口不仅可以定义对象, 还可以定义函数:
// 声明接口interface Core {(n:number, s:string):[number,string]}// 声明函数遵循接口定义const core:Core = (a,b)=>{return [a,b];}
用接口定义类
先简单看下如何给类定义接口, 后面的课程具体讲类:
// 定义interface Animate {head:number;body:number;foot:number;eat(food:string):void;say(word:string):string;}// implementsclass Dog implements Animate{head=1;body=1;foot=1;eat(food){console.log(food);}say(word){return word;}}
交叉类型(&)
交叉类型是将多个类型合并为一个类型, 表示”并且“的关系,用&连接多个类型, 常用于对象合并:
interface A {a:number};interface B {b:string};const a:A = {a:1};const b:B = {b:'1'};const ab:A&B = {...a,...b};
联合类型(|)
交叉类型也是将多个类型合并为一个类型, 表示”或“的关系,用|连接多个类型:
function setWidth(el: HTMLElement, width: string | number) {el.style.width = 'number' === typeof width ? `${width}px` : width;}
