高级类型
最后更新于:2022-04-02 03:28:17
[TOC]
## 交叉类型(Intersection Types)
交叉类型是将多个类型合并为一个类型。 这让我们可以把现有的多种类型叠加到一起成为一种类型,它包含了所需的所有类型的特性
```
function extend(first: T, second: U): T & U {
let result = {};
for (let id in first) {
(result)[id] = (first)[id];
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
(result)[id] = (second)[id];
}
}
return result;
}
class Person {
constructor(public name: string) { }
}
interface Loggable {
log(): void;
}
class ConsoleLogger implements Loggable {
log() {
// ...
}
}
var jim = extend(new Person("Jim"), new ConsoleLogger());
var n = jim.name;
jim.log();
```
## 联合类型(Union Types)
bad
```
function demo(a:any){
console.log(a);
}
```
good
```
function demo(a:string|number){
console.log(a);
}
```
### 值是联合类型
只能访问此联合类型的所有类型里共有的成员
```
interface Bird {
fly();
layEggs();
}
interface Fish {
swim();
layEggs();
}
function getSmallPet(): Fish | Bird {
// ...
}
let pet = getSmallPet();
pet.layEggs(); // 公共
pet.swim(); // errors
```
## 类型别名
```
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
if (typeof n === 'string') {
return n;
}
else {
return n();
}
}
```
### 用 tpye 约束参数值
```
type test="123"|"abc"
class demo{
d(p:test):test{
return p
}
}
let dd =new demo();
dd.d("123");
dd.d("abcc");//error
```
### 可辨识联合(Discriminated Unions)
```
interface A {
kind: "A";
aa: string;
}
interface B{
kind:"B";
bb:string;
}
interface C{
kind:"C";
cc:number
}
type kind = A|B|C
function foo(k:kind){
switch (k.kind){
case "A":return k.aa
case "B":return k.bb
case "C":return k.cc
}
}
```
';