企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 交叉类型(Intersection Types) 交叉类型是将多个类型合并为一个类型。 这让我们可以把现有的多种类型叠加到一起成为一种类型,它包含了所需的所有类型的特性 ``` function extend<T, U>(first: T, second: U): T & U { let result = <T & U>{}; for (let id in first) { (<any>result)[id] = (<any>first)[id]; } for (let id in second) { if (!result.hasOwnProperty(id)) { (<any>result)[id] = (<any>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 } } ```