美文网首页
ts学习笔记

ts学习笔记

作者: 无心之水 | 来源:发表于2021-07-05 16:40 被阅读0次

学习好文

interface

  1. 在接口中定义方法
    定义传入参数和返回的类型
interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}
  1. interface的合并
    与类型别名不同,接口可以定义多次,会被自动合并为单个接口。
interface Point { x: number; }
interface Point { y: number; }

const point: Point = { x: 1, y: 2 };

断言

<>或者as

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;
let strLength: number = (someValue as string).length;

在jsx里只能使用as语法

readonly修饰符

表示属性只读,无法被赋值并且无法赋给其他变量:

let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!

可以利用断言重新赋值:

a = ro as number[];

类的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 是只读的.

protected修饰符

protected成员在派生类中仍然可以访问。
构造函数也可以被标记成 protected。 这意味着这个类不能在包含它的类外被实例化,但是能被继承。比如


// Employee 能够继承 Person
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");
let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.

枚举

枚举类型与数字类型兼容,并且数字类型与枚举类型兼容。不同枚举类型之间是不兼容的。比如,

enum Status { Ready, Waiting };
enum Color { Red, Blue, Green };

let status = Status.Ready;
status = Color.Green;  // Error

相关文章

  • Typescript

    TypeScript(TS)部分 TypeScript学习笔记

  • 2019-10-16

    https://ts.xcatliu.com/introduction/get-typescript 学习笔记 入...

  • ts - 学习笔记

    默认 变量 常量 枚举 联合 node 第三方库 方法 变量 常量 枚举 联合 number 数值 string ...

  • TS学习笔记

    1.环境搭建 1.安装node.js,百度搜索node官网下载node,然后安装,过程比较简单,不再赘述 2.下载...

  • ts学习笔记

    学习好文[https://juejin.cn/post/6872111128135073806] interfac...

  • ts 学习笔记

    1、interface和type的区别 interface可定义多次,对象会被合并;type不允许重复定义 int...

  • ts学习笔记

    配置 tsc --init 生成tsconfig.json vscode 任务-运行任务 tsc:监视-tscon...

  • TS初学笔记

    整理之前学习ts时的一些笔记。 安装 或者安装 ts-node ,将以上两步合并为一步 ts-node hello...

  • TypeScript学习记录- 数据类型基础

    TS 学习笔记记录 相关文档 TypeScript 入门教程-xcatliu JavaScript高级程序设计(第...

  • 【TS学习笔记】TypeScript入门学习笔记

    1. 数据类型与推断 TypeScript 在声明变量或是函数时需要添加约束也叫类型注释。支持的基本类型和引用类型...

网友评论

      本文标题:ts学习笔记

      本文链接:https://www.haomeiwen.com/subject/hbtldltx.html