TS官方文档小记

2021-01-24  本文已影响0人  Gaarahan

1. TS修改ReadonlyArray

let a: ReadonlyArray<number> = [1, 2];

let b = a as number[];

b.push(3);

console.log(a);  // [1 ,2 ,3]
console.log(b);  // [1 ,2 ,3]
// 编译后
var a = [1, 2];
var b = a;
b.push(3);
console.log(a);
console.log(b);

2. 接口描述了类的公共部分,而不是公共和私有两部分。 它不会帮你检查类是否具有某些私有成员。

interface MyKlass {
    name: string;
    age: number;
}

// ERROR: Class 'Test' incorrectly implements interface 'MyKlass'.
//  Property 'age' is private in type 'Test' but not in type 'MyKlass'.
class Test implements MyKlass {  
    name: 'han';
    private age: 1
}

3. 混合类型

interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): Counter {
    let counter = <Counter>function (start: number) { };
    counter.interval = 123;
    counter.reset = function () { };
    return counter;
}

let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;

4. 关于类

class Test {
    static age = 18;
    public name = 'gaarahan';
}

const testIns = new Test();

const instanceTypeTest: Test = testIns;
/* Property 'age' is a static member of type 'Test' */
console.log(instanceTypeTest.age);   // Error: Test 是实例的类型,实例上是访问不到静态属性的

/*
Type 'Test' is not assignable to type 'typeof Test'.
  Property 'prototype' is missing in type 'Test'.
*/
const klassTypeTest: typeof Test = testIns;  // 类的类型(typeof Test)与实例类型(Test)并不兼容

const klassTypeTest1: typeof Test = Test;  // typeof Test 与 Test 是兼容的
console.log(klassTypeTest1.age);  

5. 显式的使用this以支持类型检查

interface ITest {
  name: string
}

class Test implements ITest {
    name: 'han';
    saySth(this: Test) {
        return () => {
          alert(this.name)
        }
    }
}

const t = new Test();
const saySth = t.saySth();

saySth();

6. 对于工厂函数来说,我们也可以检查传入构造函数的参数,来避免出错

class Clock {
    date: Date;
    constructor(date: Date) {
        this.date = date;
    }
}

function factoryWithoutType<T>(c): T {
    return new c('han');  // 使用错误的参数来初始化
}

function factoryWithType<T>(c: { new (name: string) }): T {
    return new c('han');   // 使用错误的参数来初始化
}

const clockHan1 = factoryWithoutType<Clock>(Clock);
console.log(clockHan1.date);  // 'han'

const clockHan2 = factoryWithType<Clock>(Clock); // 传入的参数类型检查报错

7. const枚举 与 外部枚举

// 编译前
const enum Enum {
    A = 1
}
console.log(Enum.A);
console.log(Enum[1]); // Error: A const enum member can only be accessed using a string literal.
// --------------------------------------

enum Test {
    A
}
console.log(Test.A);
// 编译后
console.log(1 /* A */);
console.log(Enum[1]);
// --------------------------------------
var Test;
(function (Test) {
    Test[Test["A"] = 0] = "A";
})(Test || (Test = {}));
console.log(Test.A);
上一篇 下一篇

猜你喜欢

热点阅读