ts数据类型

373 阅读4分钟

(一)原始数据类型

ts 中 :后面都是类型

(1)、布尔值 boolean

let isDone: boolean = true;

(2)、数字 number

和JavaScript一样,TypeScript里的所有数字都是浮点数。 这些浮点数的类型是 number。 除了支持十进制和十六进制字面量,TypeScript还支持ECMAScript 2015中引入的二进制和八进制字面量。

let decLiteral: number = 6;

(3)、字符串 string

let str: string = '';

(4)、undefined和null

undefined和null是所有类型的子类型,可以把他赋值给其他类型

(5)、any

表示变量可以是任意类型

(二)、非原始数据类型

(1)、数组

有两种方式可以定义数组。 第一种,可以在元素类型后面接上 [],表示由此类型元素组成的一个数组

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

第二种是使用数组泛型 Array<元素类型>

let list: Array<number> = [1,2,3];

类数组,有数据的属性如length,但无属性的方法

function test (){
  console.log(arguments); // IArguments ts预置类型vscode支持联想
  const htmlCollection: htmlCollection; // htmlCollection ts预置类型
}

(2)、元组 Tuple

元组类型允许表示一个已知数据类型和长度的数组

let x: [number, string] = [10, 'ww'];

当访问一个已知索引的元素,会得到正确的类型

console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

当访问一个越界的元素,会使用联合类型替代:

x[3] = 'world'; // OK, 字符串可以赋值给(string | number)类型

console.log(x[5].toString()); // OK, 'string''number' 都有 toString

x[6] = true; // Error, 布尔不是(string | number)类型

(3)、object

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

interface 用于定义对象(object)类型 ,对象的类型是由普通类型组合在一起

1、对对象的形状(shape)进行描述

2、对类(class)进行抽象

3、duck typing(鸭子类型)(如果他会游泳会嘎嘎叫就把他推断成鸭子)

接口命名 推荐首字母大写,有的前面加I 1、对 对象的形状进行描述 他有哪些属性和方法

interface IPernson{ // 无=等于号
  readonly id: number;//只读属性 readonly 用在属性上 const 用在变量上
  name: string; // 分号 ,对象里才是逗号
  age?: number; // 可选
}
let weini: IPernson = {
      id: 123,
      name: 'weini',
      age: 18,
  }
  
  

2、对类的行为进行抽象 用implements!!

interface Radio {
    switchRadio(): void;
}

interface Battery {
    checkBattery()
}

interface RadioWithBattery extends Radio{
    checkBattery()
}

class Car implements Radio {
    switchRadio(){
        console.log('car radio.....');
    }
}

const car = new Car();
car.switchRadio()

class CellPhone implements Radio, Battery {
    switchRadio(){
        console.log('cellPhone radio....');
    }
    checkBattery(){}
}

class Phone implements RadioWithBattery{
    switchRadio(){
        console.log('cellPhone radio....');
    }
    checkBattery(){}
}
const phone = new CellPhone();
phone.switchRadio();

(4)、void

void类型和any类型相反,表示没有任何类型

function useVoid(): void {
   console.log('this is my warning message'); 
}
// 当函数没有返回值时,他的返回值类型为void

(三)类型推论、联合类型和类型断言

类型推论

let a = '123' // 把鼠标放到a上编辑器会提示let a: string,这就是ts的类型推论,推断a是string类型
a = 123; // 这里会报错 不能将类型“number”分配给类型“string”

联合类型

let numberOrString: number | string;

类型断言

let numberOrString: number | string;
function getLength(input: string | number): number {
  const str = input as string // 类型断言,这样写告诉ts我只到它的类型,ts就不会报错
  if (str.length) {
    return str.length
  } else {
    const number = input as number;
    return number.toString().length
  }
}

// type guard
function getLength2(input: string | number) : number{
  if (typeof input === 'string') {
    return input.length
  } else {
    return input.toString().length;
  }
}

(四)、枚举 enum

enum类型是对javascript标准数据类型的一个补充(和function、class一样定义变量)。使用枚举类型可以为一组数据赋予友好的名字,我们可以由枚举的值得到它的名字。定义一系列常量

enum Color {Red, Green, Blue};
const red: Color = Color.Red; // 0

默认情况下,从0开始为元素编号,也可以手动指定成员的值。

enum Color {Red = 1, Green, Blue};
const green: Color = Color.Green; // 2
const colorName: string = Color[2]; // Green
 enum Direction {
   Up = "UP",
   Down = 'DOWN',
   Left = 'LEFT',
   Right = 'RIGHT',
}

console.log('Direction.Up,,,,,,',Direction.Up); // UP
console.log('Direction["Up"],,,,,,',Direction["Up"]); // UP
const a: Direction = Direction.Up;
const b: Direction = Direction['Up'];
const c: string = Direction.Up;
const d: string = Direction['Up'];
console.log(a,b,c,d); // UP UP UP UP
const value = 'UP';
if(Direction.Up === value){
   console.log('go up!'); //go up!
}

常量枚举, 每项值为常量的枚举可以使用常量枚举,可以提升性能

const enum Direction { // const
    Up = "UP",
    Down = 'DOWN',
    Left = 'LEFT',
    Right = 'RIGHT',
}
const value = 'UP';
if(Direction.Up === value){
    console.log('go up!'); //go up!
}

(五)、类型别名、字面量和交叉类型

类型别名: 给类型起一个快捷方式类型的名称

// type aliase
let sum: (x: number, y: number) => number
const result = sum(1,2)
type PlusType = (x: number, y: number) => number
let sum2: PlusType
const result2 = sum2(2, 3)

字面量

const str: 'name' = 'name'
const number: 1 = 1
type Directions = 'Up' | 'Down' | 'Left' | 'Right'
let toWhere: Directions = 'Left'

交叉类型:将几种类型合并起来

interface IName {
  name: string
  }
type IPerson = IName & { age: number }
let person: IPerson = { name: '123', age: 123 }

(六)、内置类型

ts内置的类型

//global objects
const a: Array<number> = [1,2,3]
const date = new Date()
date.getTime()
const reg = /abc/
reg.test('abc')

//build-in object
Math.pow(2, 2)

//DOM and BOM
let body = document.body
let allLis = document.querySelectorAll('li')
allLis.keys()

document.addEventListener('click', (e) => {
 e.preventDefault()
})

(七)、partial

取其中的一部分

//Utility Types
interface IPerson {
  name: string
  age: number
}
let viking: IPerson = { name: 'viking', age: 20 }
type IPartial = Partial<IPerson>
let viking2: IPartial = { name: 'viking' }
type IOmit = Omit<IPerson, 'name'>
let viking3: IOmit = { age: 20 }