TypeScript初学

50 阅读2分钟

1.基本类型变量的写法

let a: Array<string> = ["1"];
let a1: string[] = ["1"];

type foc11 = Array<string> | number[];
let a2: foc11 = [1];
let a3: foc11 = [""];

enum FPC {
  name1 = 1,
  name2 = 2,
}

let b: FPC = FPC.name1;
let b1: FPC = 1;

image.png

2.函数

// 函数定义的各个写法

// 写法1
let d0: () => void;
d0 = () => {
  return 1; // 不报错
};

// 写法2
let d2 = function (A: number): void {
  // return 1 // 报错
};
d2(1);

// 写法3
type d3 = (A: number) => void;
let d33: d3 = () => {
  return 1; // 不报错
};
d33(1);

// 写法4
interface d4 {
  (A: number): void;
}
let d44: d4 = () => {
  return 1; // 不报错
};

// 写法5
declare function d1(): void;
d1();

image.png

3.对象

// 写法1
type obj1 = {
  readonly name: string;
  age: number;
} & {
  height: number;
  
};

let theO: obj1 = {
  name: "",
  age: 3,
  height: 13,
}; 
// theO.name = 1 抱错

// 写法2
interface Iobj1 {
  readonly name: string;
  age: number;
}
interface Iobj1 {
  height: number;
}

let theI: Iobj1 = {
  name: "",
  age: 3,
  height: 13,
};

// theI.name = 1 抱错

image.png

4.class类

// 类写法1
class FPC_1 {
  public name: string = "fpc";
  protected age = 11;
  private height = 111;
}

let A: FPC_1 = new FPC_1();
A.name;
A.age; // 报错 属性“age”受保护,只能在类“FPC_1”及其子类中访问。ts(2445)
A.height; // 报错 属性“height”为私有属性,只能在类“FPC_1”中访问。ts(2341)

// 类写法2
interface IFPC2 {
  name: string;
}

interface IFPC3 extends IFPC2 {
  age: number;
}

interface IFPC4 {
  height: number;
}

class YC implements IFPC3, IFPC4 {
  public name = "1"; // 接口定义的都是public,
  private age = 2; // 报错  属性“age”在类型“YC”中是私有属性,但在类型“IFPC3”中不是
  public height = 3;
}

// 类写法3  抽象类
abstract class YCPC {
  names: string;
  abstract ages: number;
  height: number;

  abstract getAll() {} // 报错, 方法“getAll”不能具有实现,因为它标记为抽象。ts(1245)
  abstract getAll2(): void; 

  getAll3() {} // 具体实现
}

class SON extends YCPC {
  //报错  非抽象类“SON”缺少“YCPC”的以下成员的实现: 'ages', 'getAll', 'getAll2'。ts(2654)
}
class SON2 extends YCPC {
  ages = 1;
  getAll() {}
  getAll2() {}
}

let ddd = new SON2();
ddd.getAll3();

image.png