编译

  • tsc demo.ts 主动编译
  • webstrom 设置自动编译

image.pngimage.png

基本类型

1. string

  1. let name: string = 'joe';

2. number

  1. let num: number = 100;

3. boolean

  1. let bool: boolean = true;

4. null,undefined

  • 默认情况是所有类型得子类型

    5. enum

    1. enum Color = {a: 1, b: 2}
    2. let aa: Color = Color.a;
    3. Color[1] // a

    6. void

  • 函数没有返回值,用这个声明一个变量没什么意义,只能赋值undfined和null

    1. function test(): void {
    2. console.log('test');
    3. }

    7. never

  • 表示永远不存在的类型

    8. object

  • 表示非原始类型

    9. 断言

  • 比如你的变量是 let name: any = 'joe',使用的时候你可以用断言声明他的类型,下面两种用法一样的

    • <string>name
    • name as string 在用jsx的时候只能用这个 as 语法

      10. 元组

  • 已知道元素数组的类型和数量,顺序也要

    1. let x: [string, number];
    2. x = ['hello', 10]; // OK
    3. x = [10, 'hello']; // Error // Initialize it incorrectly

    接口

  • 接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约

  • 接口名约定大驼峰写法

    简单例子

    ```javascript interface ObjRules{ // 定义接口 name: string, age: number }

let obj: ObjRules = { // 使用接口限制变量类型 name: ‘joe’, age: 20 }

  1. <a name="niBpe"></a>
  2. ### 变量属性比约定接口类型还多的时候
  3. - 只要使用了接口,例如` function test(obj: interface) {}` 这个obj的参数里面的**条件有满足就行了**,里面的**属性可以多但是不能少**,但是我们传了属性却会报错,看下面的图片
  4. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/683622/1641024529911-02d416a4-d9f7-4673-8f0e-74358f10e0f6.png#clientId=u13e6ccd2-f339-4&from=paste&height=538&id=u396f4973&margin=%5Bobject%20Object%5D&name=image.png&originHeight=538&originWidth=960&originalType=binary&ratio=1&size=57464&status=done&style=none&taskId=u1f57c727-29c4-494d-82d5-0ba46e380b2&width=960)
  5. ```javascript
  6. // 上面配图的代码
  7. interface Test {
  8. name: string;
  9. age: number;
  10. }
  11. function test(obj: Test):void {
  12. console.log('测试1')
  13. }
  14. test({name: 'joe', age: 20});
  15. test({name: 'joe', age: 20, address: 'Guangzhou'});

:::success

  • 上面的这个图是因为,对象字面量会被特殊对待而且会经过额外属性检查,当将它们赋值给变量或作为参数传递的时候。 如果一个对象字面量存在任何“目标类型”不包含的属性时,你会得到一个错误…想要绕开这些检查
    • 使用断言
    • 增加前面索引
    • 把要传的参数先定义成变量 :::

      1. 使用断言 as

      1. // 使用了断言 as Test,告诉浏览器我们清楚的知道这个就是 Test 类型,不要给我报错
      2. test({name: 'joe', age: 20, address: 'Guangzhou'} as Test);

      2. 但是最好的方式是加一个索引签名,实际不要绕开检查,否则容易出问题 [propName: string]: any

      1. interface Test {
      2. name: string;
      3. age: number;
      4. [propName: string]: any; // 这里设置了一个索引签名
      5. }

      3. 把要传的参数定义成变量

      ```javascript const obj: Test = {name: ‘joe’, age: 20, address: ‘Guangzhou’}; test(obj);
  1. <a name="om76b"></a>
  2. ### 可选属性 `?:`
  3. ```javascript
  4. interface Test {
  5. name?: string; // 就是冒号前面加一个问号 ?:
  6. age?: number;
  7. }
  8. 例如 obj.colo => 这样就会提示
  • 虽然设置了可选,但是最少最少要传到可选的其中一项, 定义了在函数里面调用的时候,要是属性名写错也会提示一下你,例如

image.png

  1. // 上图函数代码
  2. function test(obj: Test):void {
  3. console.log(obj.nam) //这里就会提示你
  4. }

可读属性 readonly

  1. interface Test {
  2. readonly name: string;
  3. readonly age: number;
  4. }
  • 属性可读不可修改,等于把一个对象里面的属性变成了const类型,即使是你的属性里面是对象,里面又对象,包含很多层也是改不了的
  • 数组的不可修改let arr: ReadonlyArray<number> = [1,2,3,4,5]就什么都不能改了,赋值给别的变量也不能改,但是可以用断言可以重写,看例子

    1. let arr: ReadonlyArray<number> = [1,2,3,4,5];
    2. let arr2 = arr as number[]; // 这个时候这个arr2 也就是复制了一个arr然后arr2可以进行修改了

    函数类型

    1. interface Test {
    2. (name: string, age: number): boolean // 定义一个构造函数类型
    3. }
    4. let test: Test = function (n, a): boolean {
    5. //let fn: Fn = function (n: string, a: number) 也可以定义上变量类型,不定义也行,ts会自动推断出来
    6. return typeof n === 'string' && typeof a === 'number';
    7. }
    8. test('joe', 20);

    类里面得构造器得参数加public等于成员变量

    1. class Test {
    2. constructor(public name, public ok) {}
    3. // 这个 public name 也是等于成员变量,this.name 这样
    4. }

    类实现接口 implements

  • TypeScript能够用它来明确的强制一个类去符合某种契约 ```javascript interface Test { // 定义了接口 name: string, test(name: string, age: number): boolean }

class One implements Test{ // 这里去实现接口,要把定义的成员和方法都实现 name: string; test(name: string, age: number): boolean { return false; } constructor() { } }

  1. <a name="xN61m"></a>
  2. ### 构造器签名去定义一个接口并试图定义一个类去实现这个接口出错问题
  3. - 类的静态部分的和实例部分,当一个类实现一个接口,只会对其实例部分进行检测,如果对constructor检查是不行的因为静态不部分,例如你会注意到,当你用构造器签名去定义一个接口并试图定义一个类去实现这个接口时会得到一个错误,如下![image.png](https://cdn.nlark.com/yuque/0/2022/png/683622/1641047035977-61267e67-ef6f-4a33-b972-46fcb03a4f1e.png#clientId=u13e6ccd2-f339-4&from=paste&height=339&id=u96477fab&margin=%5Bobject%20Object%5D&name=image.png&originHeight=339&originWidth=809&originalType=binary&ratio=1&size=32337&status=done&style=none&taskId=u29851015-65d2-4669-978b-7158590138a&width=809)
  4. ```javascript
  5. // 错误方式
  6. interface Test { // 1. 定义接口
  7. new(name: string, age: number)
  8. }
  9. class One implements Test{ // 2. 企图直接实现接口通过对构造函数的限定,这里是会报错的
  10. constructor(name, age) {
  11. this.name = name;
  12. this.age = age;
  13. }
  14. }
  15. // 正确方式
  16. interface Test { // 1. 定义接口1,想限定构造函数的
  17. new(name: string, age: number)
  18. }
  19. interface TestInterface { // 2. 再定义一个接口2,限定成员和方法的
  20. test();
  21. }
  22. function createTest(creator: Test, name: string, age: number) { // 3. 定义一个方法,接收一个类和类构造函数需要的参数,返回一个组成的对象出去
  23. return new creator(name, age);
  24. }
  25. class One implements TestInterface{ // 4. 定义一个类实现接口2并且按照接口1去先构造函数
  26. constructor(n: string, a: number) {
  27. }
  28. test() {
  29. console.log('one')
  30. }
  31. }
  32. class Two implements TestInterface{
  33. constructor(n: string, a: number) {
  34. }
  35. test() {
  36. console.log('two')
  37. }
  38. }
  39. let c = createTest(One, 'joe', 20); // 5. 再调用方法得到规定的对象
  40. let c1 = createTest(Two, 'CINDY', 33);
  41. c.test();
  42. c1.test();
  43. // 虽然不知道这样有什么使用场景。。。

接口继承

一个接口可以去继承多个接口

  1. interface One {
  2. name: string
  3. }
  4. interface Two {
  5. address: string
  6. }
  7. interface Three {
  8. age: number
  9. }
  10. interface Four {
  11. isMale: boolean
  12. }
  13. interface Person extends One, Two, Three, Four{
  14. area: string
  15. }
  16. const p1:Person = {name: 'joe', address: 'guangzhou', age: 20, isMale: true, area: 'guangdong'};
  17. console.log(p1)

接口继承类

  • 就是结成类的成员(变量和方法),但是不包括其实现,接口同样会继承到类的private和protected成员 ```javascript class Test { state: any; otherFn() {
    1. console.log('otherFn')
    } }

interface TestInterface extends Test{ test(): void; }

class One implements TestInterface{ state: ‘’; test() { console.log(‘test’) } otherFn() { console.log(111) } }

  1. <a name="zIKC2"></a>
  2. ## 类
  3. ```javascript
  4. class Test {
  5. test: string = '666'; // 定义成员变量
  6. constructor(name) { // 定义构造函数
  7. this.test = name;
  8. }
  9. fn (name: string): void { // 定义方法
  10. this.test = name;
  11. }
  12. }
  13. const obj1 = new Test('ha');
  14. console.log(obj1.test) // ha
  15. obj1.fn('joe');
  16. console.log(obj1.test) // joe

继承 extends

  • 就是如果父子都有构造函数,子一定要调用父的构造函数,而且是第一行就要调用 ```javascript class Father { color: string; constructor(eye) {
    1. this.color = eye;
    } }

class Son extends Father{ constructor(eye) { super(eye); } }

  1. <a name="xAtB3"></a>
  2. ### 公共,私有,和保护修饰符
  3. - `public` 默认就是这样
  4. - `private` 是不可以被外部访问道的,只能在类里面自己访问,派生类也不能访问
  5. - `protected` 可以被派生类访问,也不可以被外部访问
  6. - 构造函数也可以被标记成private。这就意味这个这类完全不能被继承了也不能实例化,等于废了。
  7. - 构造函数也可以被标记成 protected。 这意味着这个类不能在包含它的类外被实例化,但是能被继承。除了原本类可以实例化对象
  8. ```javascript
  9. // 公有
  10. class Test {
  11. public name: string;
  12. }
  13. // 私有
  14. class Test {
  15. private name: string = 'joe'; // 设置了变量私有,无法访问
  16. }
  17. new Test().name; // Property 'name' is private and only accessible within class 'Test'.
  18. class TestSon extends Test{
  19. constructor() {
  20. super();
  21. this.name; // Property 'name' is private and only accessible within class 'Test' 无法继承私有变量
  22. }
  23. }
  24. new TestSon().name
  25. // 保护
  26. class Test {
  27. protected name: string = 'joe'; // 设置了变量保护
  28. }
  29. new Test().name; // Property 'name' is protected and only accessible within class 'Test' and its subclasses.
  30. class TestSon extends Test{
  31. constructor() {
  32. super();
  33. this.name; // joe 这里访问可以,是可以被继承类内部访问到的,但是外部实例也是无法访问到的
  34. }
  35. }
  36. // 设置了构造函数保护
  37. class Test {
  38. protected constructor(name: string) { // 设置构造函数保护
  39. }
  40. }
  41. class TestSon extends Test{
  42. constructor(name) {
  43. super(name);
  44. }
  45. }
  46. new Test('name'); // 这里是无法实例化的,报错: Constructor of class 'Test' is protected and only accessible within the class declaration.
  47. new TestSon('name'); // 这里可以访问

比较两种不同的类型

  • TypeScript使用的是结构性类型系统。 当我们比较两种不同的类型时,并不在乎它们从何处而来,如果所有成员的类型都是兼容的,我们就认为它们的类型是兼容的 ```javascript class Animal { private name: string; constructor(theName: string) { this.name = theName; } }

class Rhino extends Animal { constructor() { super(“Rhino”); } }

class Employee { private name: string; constructor(theName: string) { this.name = theName; } }

let animal = new Animal(“Goat”); let rhino = new Rhino(); let employee = new Employee(“Bob”);

animal = rhino; animal = employee; // 错误: Animal 与 Employee 不兼容. 因为即使他有private,但是并非来自Animal所以是不兼容的

  1. <a name="JDSqc"></a>
  2. ### readonly修饰符:
  3. - 必须声明时候实例化或者在构造函数实例化,并且只读
  4. - 声明时候可以赋值
  5. - 构造函数可以赋值
  6. - 其他时候只读
  7. ```javascript
  8. class Octopus {
  9. readonly numberOfLegs: number = 8;
  10. constructor(readonly name: string = 'joe') { // 这个就是等于声明类的成员变量了 readonly name: string = 'joe'
  11. }
  12. }

存取器

  • 可以根据自己的需求设置set和get ```javascript class Test { private _name: string; get name(): string {
    1. return this._name;
    } set name(name: string) {
    1. this._name = name;
    } }

let t1 = new Test(); t1.name = ‘joe’; console.log(t1.name)

  1. <a name="pMbhW"></a>
  2. ### 抽象类 `abstract`
  3. - 和接口差不多,但是有关键字声明,而且不能实例化
  4. ```javascript
  5. abstract class Test {
  6. abstract go (name: string): void;
  7. }
  8. class One extends Test{
  9. go(name: string): void {
  10. }
  11. }
  12. let obj: Test = new One(); // 允许把类型声明为超类的类型
  13. let obj1: Test = new Test(); // 不允许实例化抽象类

函数

定义函数的完整类型

  1. let getName: (name: string, age?: number) => string = function (name: string, age: number) {
  2. return String(name + age);
  3. }

可选参数

  1. function f(name: string, age?: number) {}
  2. f('xixi')
  1. function f (name: string, age?: number): void {}
  2. function f (name: string, age:number = 20): void {}
  3. 这两个其实是一样可以忽略第二个参数

TODO

接口

  • 可索引类型 这个不太懂
  • 混合类型