Ts基础

发布于 2023-03-19  40 次阅读


类型注解

布尔值 boolean

let isDone: boolean = false;

数字 number

let decLiteral: number = 6; // 十进制
let hexLiteral: number = 0xf00d; // 十六进制
let binaryLiteral: number = 0b1010; // 二级制
let octalLiteral: number = 0o744; // 八进制

字符串 string

let myName: string = "bob";
myName = "smith";

let sentence: string = `Hello, my name is ${ myName }.

任意类型 any

  • 在不确定某个变量会是什么类型的情况下,可以注解为 any
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
  • 不要滥用 any
let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
  • 如果 any 给 对象 的话,会导致不能提示对象上原有的属性和方法
let obj: {
  num: string,
  toString: () => void
} = {
  num: '123',
  toString: function() {}
}
// 在获取 obj. 时,就会有提示,说 obj 下边有 num、toString 两个属性

let obj: any = {
  num: '123',
  toString: function() {}
} // 改为 any 后,获取 obj. 时就没有提示了
  • 当你只知道一部分数据的类型时,any类型也是有用的。 比如你有一个数组,它包含了不同的类型的数据:
let list: any[] = [1, true, "free"];

list[1] = 100;
  • 未给初始值的变量,类型为 any
let a;
a = '123';
a = 123;

void

  • 函数没有返回值时使用
function warnUser(): void {
    console.log("This is my warning message");
}

null 和 undefined

TypeScript里,undefinednull 两者各自有自己的类型分别叫做 undefinednull。 和 void 相似,它们的本身的类型用处不是很大:

// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;

默认情况下nullundefined是所有类型的子类型。 就是说你可以把 nullundefined 赋值给number类型的变量。

然而,当你指定了--strictNullChecks标记,nullundefined只能赋值给void和它们各自。 这能避免 很多常见的问题。 也许在某处你想传入一个 stringnullundefined,你可以使用联合类型 string | null | undefined 。

never

never类型表示的是那些永不存在的值的类型。

  • 例如
    • 报错
    • 死循环
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
    throw new Error(message);
}

// 推断的返回值类型为never
function fail() {
    return error("Something failed");
}

// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
    while (true) {
    }
}

object

object表示非原始类型,也就是除number,string,boolean,symbol,null或undefined之外的类型。

数组 []

写法方式

  1. 类型[]: number[]
  2. Array<类型>: Array<number>
  3. interface
let arr: number[] = [1, 2, 3];
let arr2: (string | number)[] = [1, 2, '3'];
let list: Array<number> = [1, 2, 3];
interface List {
  [index: number]: number
}

let list: List = [1, 2, 3];

// or 联合类型

interface List {
  [index: number]: number | string
}

let list: List = [1, 2, 3, '4'];

类数组

  • 官方定义
  • 自定义
interface Args {
  [index: number]: any;
  length: number;
}

function test() {
  let args: Args = arguments;
}

函数

// 函数声明
function add(x: number, y: number): number {
    return x + y;
}

// 函数表达式
let myAdd = function(x: number, y: number): number { return x + y; };

// 完整函数类型
let myAdd: (x: number, y: number) => number =
    function(x: number, y: number): number { return x + y; };
// 可选参数
function buildName(firstName: string, lastName?: string) {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}

let result1 = buildName("Bob");  // works correctly now
let result2 = buildName("Bob", "Adams", "Sr.");  // error, too many parameters
let result3 = buildName("Bob", "Adams");  // ah, just right
// 默认参数(默认参数都放后边,不要放必填参数前边)
function buildName(firstName: string, lastName = "Smith") {
    return firstName + " " + lastName;
}

let result1 = buildName("Bob");                  // works correctly now, returns "Bob Smith"
let result2 = buildName("Bob", undefined);       // still works, also returns "Bob Smith"
let result3 = buildName("Bob", "Adams", "Sr.");  // error, too many parameters
let result4 = buildName("Bob", "Adams");         // ah, just right
// 剩余参数
function buildName(firstName: string, ...restOfName: string[]) {
  return firstName + " " + restOfName.join(" ");
}

let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");

函数中的 this

  • 问题
let deck = {
    suits: ["hearts", "spades", "clubs", "diamonds"],
    cards: Array(52),
    createCardPicker: function() {
        return function() {
            let pickedCard = Math.floor(Math.random() * 52);
            let pickedSuit = Math.floor(pickedCard / 13);

            return {suit: this.suits[pickedSuit], card: pickedCard % 13};
            // 上边 return 对象中的 this 指向 window or undefined
        }
    }
}

let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();

alert("card: " + pickedCard.card + " of " + pickedCard.suit);
  • 解决
    • 往例子里添加一些接口,Card 和 Deck,让类型重用能够变得清晰简单些
interface Card {
    suit: string;
    card: number;
}
interface Deck {
    suits: string[];
    cards: number[];
    createCardPicker(this: Deck): () => Card;
}
let deck: Deck = {
    suits: ["hearts", "spades", "clubs", "diamonds"],
    cards: Array(52),
    // NOTE: The function now explicitly specifies that its callee must be of type Deck
    createCardPicker: function(this: Deck) {
        return () => {
            let pickedCard = Math.floor(Math.random() * 52);
            let pickedSuit = Math.floor(pickedCard / 13);

            return {suit: this.suits[pickedSuit], card: pickedCard % 13};
        }
    }
}

let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();

alert("card: " + pickedCard.card + " of " + pickedCard.suit);

函数中的重载

  • 表明一个函数针对不同类型有不同注解
  • function 之间不能有空格,上边两个 function 是注解下边 function 主体的
  • 表意更清楚

  • 在子类的 constructor 中使用 supersuper 指向 父类.prototype.constructor
  • 在子类的非 constructor 方法中使用 supersuper 指向 父类.prototype
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");

继承

// 父类 -- 基类
class Animal {
    move(distanceInMeters: number = 0) {
        console.log(`Animal moved ${distanceInMeters}m.`);
    }
}

// 子类 -- 派生类
class Dog extends Animal {
    bark() {
        console.log('Woof! Woof!');
    }
}

const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();
class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

class Snake extends Animal {
    constructor(name: string) { 
      super(name);
      // 这里的 super 是 Animal.constructor ,也就是 Animal 的构造函数
      // super(name) 返回的是子类 Snake 的实例, 即 super 内部的 this 指的 Snake 实例
      // 这里的 super(name) 相当于
      // Animal.prototype.constructor.call(this, name);
    }
    move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
      // 这里的 super 是 Animal.prototype
      // super.move() 相当于 Animal.prototype.move()
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 45) {
        console.log("Galloping...");
        super.move(distanceInMeters);
    }
}

let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);

类成员的修饰符

  • public 公共的成员属性
    • 自身可调用
    • 子类可调用
    • 实例可调用
  • protected
    • 自身可调用
    • 子类可调用
  • private 私有属性
    • 自身可调用
class Animal {
    public name: string;
    public constructor(theName: string) { this.name = theName; }
    public move(distanceInMeters: number) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}
class Animal {
    private name: string;
    constructor(theName: string) { this.name = theName; }
}

new Animal("Cat").name; // 错误: 'name' 是私有的.
class Person {
    protected name: string;
    constructor(name: string) { this.name = name; }
}

class Employee extends Person {
    private department: string;

    constructor(name: string, department: string) {
        super(name)
        this.department = department;
    }

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // 错误

readonly 修饰符

可以使用 readonly 关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。

class Octopus {
    readonly name: string;
    readonly numberOfLegs: number = 8;
    constructor (theName: string) {
        this.name = theName;
    }
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.

参数属性

在上面的例子中,我们必须在Octopus类里定义一个只读成员 name 和一个参数为 theName 的构造函数,并且立刻将 theName 的值赋给 name,这种情况经常会遇到。 参数属性可以方便地让我们在一个地方定义并初始化一个成员。 下面的例子是对之前 Octopus 类的修改版,使用了参数属性:

class Octopus {
    readonly numberOfLegs: number = 8;
    constructor(readonly name: string) {
    }
}

注意看我们是如何舍弃了 theName,仅在构造函数里使用 readonly name: string 参数来创建和初始化 name 成员。 我们把声明和赋值合并至一处。

参数属性通过给构造函数参数前面添加一个访问限定符来声明。 使用 private 限定一个参数属性会声明并初始化一个私有成员;对于 public 和 protected 来说也是一样。

存取器

  • 不使用存取器写法
class Employee {
  fullName: string;
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
  console.log(employee.fullName);
}
  • 使用存取器写法
let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    alert(employee.fullName);
}

静态属性

  • 只能通过 类 调用;无法通过实例调用
class Grid {
    static origin = {x: 0, y: 0};
    calculateDistanceFromOrigin(point: {x: number; y: number;}) {
        let xDist = (point.x - Grid.origin.x);
        let yDist = (point.y - Grid.origin.y);
        return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
    }
    constructor (public scale: number) { }
}

let grid1 = new Grid(1.0);  // 1x scale
let grid2 = new Grid(5.0);  // 5x scale

console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));

抽象类

  • 用处
    • 能够提供其他类的基类
  • 特性
    • 无法创建实例
    • 抽象类中的抽象方法一定要有实现
abstract class Animal {
    abstract makeSound(): void; // 每个动物的叫法不一样,交给继承抽象类的类自己去实现
    move(): void {
        console.log('roaming the earch...');
    }
}

class Snack extends Animal {
  move(): void {
    // 重写
  }
  makeSound(): void {} // 必须实现抽象类的抽象方法 makeSound
}
class Rhino extends Animal {
  // move(): void {} // 可以不实现
  makeSound(): void {} // 必须实现抽象类的抽象方法 makeSound
}

把类当做接口使用

类定义会创建两个东西:类的实例类型和一个构造函数。 因为类可以创建出类型,所以你能够在允许使用接口的地方使用类。

class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};

高级类型

联合类型

let a: string | number;
  • 联合类型中的不是共有的属性是会报错的
function test(a: number | string) {
  return a.split('');
}
  • 在赋值的时候确认类型
let a: string | number;
a = '12';
console.log(a.length); // 可以
a = 12;
console.log(a.length); // 错误提示 数字 12 没有 length 属性
最后更新于 2023-07-20