交叉类型
const a1 = <T, U>(arg1: T, arg2: U): T & U => {
let res = {} as T & U;
res = Object.assign(arg1, arg2);
return res;
};
a1({ a: 1 }, { b: "abc" });
联合类型
const getLen = (content: number | string): number => {
if (typeof content === "string") {
return content.length;
} else {
return content.toString().length;
}
};
类型保护
function isString(value: number | string): value is string {
return typeof value === "string";
}
if (isString(item)) {
console.log("item is string:", item.length);
} else {
console.log("item is string:", item.toFixed());
}
class C9_1 {
public name1 = "C9_1";
}
class C9_2 {
public name2 = "C9_2";
}
function getC9() {
return Math.random() < 0.5 ? new C9_1() : new C9_2();
}
const c9 = getC9();
if (c9 instanceof C9_1) {
console.log(c9.name1);
} else {
console.log(c9.name2);
}
type: 类型别名
type Aaa = string;
let str2: Aaa;
str2 = "abc";
字面量类型
type Name = "aaa";
type Direction = "a1" | "b2" | "c3";
function getDirectionFirstLetter(direction: Direction) {
return direction.substr(0, 1);
}
console.log(getDirectionFirstLetter("b2"));
interface Info1 {
name: Name;
}
const _info: Info1 = {
name: "aaa"
};