TS 类型系统
machao07 opened this issue · comments
马超 commented
联合类型
希望属性为多种类型之一,使用 |
作为标记,如 string | number
交叉类型
extend 是一种非常常见的模式,在这种模式中,你可以从两个对象中创建一个新对象,新对象拥有着两个对象所有的功能
function extend<T extends object, U extends object>(first: T, second: U): T & U {
const result = <T & U>{};
for (let id in first) {
(<T>result)[id] = first[id];
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
(<U>result)[id] = second[id];
}
}
return result;
}
const x = extend({ a: 'hello' }, { b: 42 });
// 现在 x 拥有了 a 属性与 b 属性
const a = x.a;
const b = x.b;
元组类型
let nameNumber: [string, number];
// Ok
nameNumber = ['Jenny', 221345];
const [name, num] = nameNumber;
// Error
nameNumber = ['Jenny', '221345'];
类型别名
type StrOrNum = string | number;
// 使用
let sample: StrOrNum;
sample = 123;
sample = '123';
// 会检查类型
sample = true; // Error
枚举
// 字符串枚举
export enum EvidenceTypeEnum {
UNKNOWN = '',
PASSPORT_VISA = 'passport_visa',
PASSPORT = 'passport',
SIGHTED_STUDENT_CARD = 'sighted_tertiary_edu_id',
SIGHTED_KEYPASS_CARD = 'sighted_keypass_card',
SIGHTED_PROOF_OF_AGE_CARD = 'sighted_proof_of_age_card'
}
类型断言
interface Foo {
bar: number;
bas: string;
}
const foo = {} as Foo;
foo.bar = 123;
foo.bas = 'hello';
双重断言
function handler(event: Event) {
const element = (event as any) as HTMLElement; // ok
}
类型保护
typeof
、instanceof
、in
typeof
function doSome(x: number | string) {
if (typeof x === 'string') {
console.log(x.substr(1)); // ok
}
}
instanceof
下面关于 class 和 instanceof 的例子:
class Foo {
foo = 123;
common = '123';
}
function doStuff(arg: Foo | Bar) {
if (arg instanceof Foo) {
console.log(arg.foo); // ok
console.log(arg.bar); // Error
}
}
doStuff(new Foo());
in
检查一个对象上是否存在一个属性
interface A {
x: number;
}
interface B {
y: string;
}
function doStuff(q: A | B) {
if ('x' in q) {
// q: A
} else {
// q: B
}
}