TypeScript-类型别名

124 阅读1分钟

类型别名

type strType = string|number|boolean;
var str:strType = "10";
str = 10;
str = true;

接口也可以采用类型别名

interface muchType1 {
    name: string
}
interface muchType2 {
    age: number
}
type muchType = muchType1 | muchType2
var obj: muchType = { name: "张三" }
var obj2: muchType = { age: 18 }
var obj3: muchType = { name: "张三", age: 18 }

限制字符串的选择

type sex = '男'|'女'
function getSex(s: sex): string {
    return s;
}
getSex('女') // 只能传 ‘男’或者‘女’