初识Typescript

100 阅读1分钟

Typescript 都有哪些类型

1.Typescript 基本类型,也就是可以被直接使用的单一类型。

  • 数字
  • 字符串
  • 布尔类型
  • null
  • undefined
  • any
  • unknown
  • void
  • object
  • 枚举
  • never

2.复合类型,包含多个单一类型的类型。

  • 数组类型
  • 元组类型
  • 字面量类型
  • 接口类型

3.如果一个类型不能满足要求怎么办?

  • 可空类型,默认任何类型都可以被赋值成 null 或 undefined。
  • 联合类型,不确定类型是哪个,但能提供几种选择,如:type1 | type2。
  • 交叉类型,必须满足多个类型的组合,如:type1 & type2。

类型都在哪里使用

在 Typescript 中,类型通常在以下几种情况下使用。

  • 变量中使用
  • 类中使用
  • 接口中使用
  • 函数中使用

在变量中使用

在变量中使用时,直接在变量后面加上类型即可。

let a: number;
let b: string;
let c: null;
let d: undefined;
let e: boolean;
let obj: Ixxx = {
  a: 1,
  b: 2,
};
let fun: Iyyy = () => {};

在类中使用

在类中使用方式和在变量中类似,只是提供了一些专门为类设计的静态属性、静态方法、成员属性、构造函数中的类型等。

class Greeter {
    static name:string = 'Greeter'
    static log(){console.log(‘log')}
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}
let greeter = new Greeter("world");

在接口中使用

在接口中使用也比较简单,可以理解为组合多个单一类型。

interface IData {
  name: string;
  age: number;
  func: (s: string) => void;
}

在函数中使用

在函数中使用类型时,主要用于处理函数参数、函数返回值。

// 函数参数
function a(all: string) {}
// 函数返回值
function a(a: string): string {}
// 可选参数
function a(a: number, b?: number) {}