typescript语法精讲一(笔记)

- 使用联合类型

联合类型保证传入的是联合中的某一个类型的值即可

function setId(id: number | string) {
  console.log(typeof id);
}

-可选类型补充

可选类型可以看作是 类型 和 undefined 的联合类型:

function print(message?: string) {
  console.log(message);
}

print();
print("message");
print(undefined);

-类型别名

针对对象,可以给对象类型起一个别名:

type Info = {
    name: string,
    age: number,
    address: string
}

function printInfo(info: Info) {
  console.log(info.name, info.age, info.address);
}

-类型断言as

有的时候ts无法获取到具体的类型信息,这时候需要我们去使用类型断言(as)

常见的应用场景:获取document的元素

const myEl = document.getElementById('img') as HTMLImageElement

myEl.src = '.....'

ts只允许断言转换为更具体或者不是很具体的类型版本,主要用于防止不可能的强制转换。

const data = 10 as string; // error
const data = (10 as unknown) as string;

-非空类型断言

某个方法传入的message可能存在undefined的时候,因此,这时候是会报错的。

function print(message?: string) {
  console.log(message.toUpperCase());
}

print("test");

非空断言使用的是!,表示可以确定某个标识符是有值的,可以跳过ts在编译阶段对它的监测。

function print(message?: string) {
  console.log(message!.toUpperCase());
}

-可选链的使用

当对象的属性不存在时,会短路,直接返回undefined,如果存在,便会继续执行。

type ParentInfo = {
    name: string,
    sonInfo?: {
      name: string,
      age?: number
    }
}

const info: ParentInfo = {
    name: "test1",
    sonInfo: {
      name: "test2",
      age: 20
    }
}

console.log(info.sonInfo?.name);

-??和!!的作用

!!操作符:
将一个其他类型转换为boolean类型;

??操作符:
空值合并操作符(??)是一个逻辑操作符,当操作符的左侧是null或者undefined时,返回其右侧操作符,否则返回左侧操作符。

const message = " ";

let flag1 = Boolean(message);
let flag2 = !!message;
const message = 'message';
const result = message ?? 'test';

console.log(result);

-字面量类型

可以将多个类型联合在一起

type Alignment = 'left' | 'right' | 'center';

function changeAlign(align: Alignment) {
    console.log(align);
}

changeAlign('left');

-字面量推理

image.png

在进行字面量推理的过程中,info的参数实际上就是一个{label: string, send: string}的过程,因此,我们无法将string赋值到函数行参的字面量上去。
1、解决方法

const info = {
    label: 'test',
    send: 'B'
} as const

function getInfo(label: string, send: 'A' | 'B')  {
    console.log(label, send);
}


getInfo(info.label, info.send);
const info = {
    label: 'test',
    send: 'B'
}

function getInfo(label: string, send: 'A' | 'B')  {
    console.log(label, send);
}


getInfo(info.label, info.send as 'B');
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容