typescipt学习笔记-常见类型

文章介绍了TypeScript的Class和类型系统的核心概念,包括静态类型检查的作用,tsc编译器的使用,类型注解的必要性,以及如何处理null和undefined。还详细讲解了可选属性、联合类型、类型别名、接口、类型断言等特性。
摘要由CSDN通过智能技术生成

学习文档:

TypeScript 之 Class(上) (yuque.com)

某个人博客 -   基础类型_TypeScript中文文档

基础类型 - TypeScript 中文手册

TypeScript 基础类型 | 菜鸟教程 (runoob.com)

一、前言

1、ts的作用:静态类型检查、非异常失败、类型工具(提供补全和错误信息)。

2、tsc: the TypeScript compiler .TypeScript编译器.

ts文件不会被直接运行,需要通过tsc编译成js文件,才能运行。编译命令:tsc xxx.ts。通过这个命令 xxx.ts 就会被编译出一个xxx.js 文件出来。

① 就算编译中类型检查报错了,是依旧会编译出结果。想要使用严格模式,可以执行命令 

tsc --noEmitOnError hello.ts

②如果类型系统可以正确判断出来类型,不需要加类型注解。

let msg = 'hello there';

// don't need  --  let msg:string

3、编译之后的js,会被 类型抹除(不再有类型注解)+降级(es6可能被降为->es3)

4、严格模式noImplicitAny(当类型被隐士推断为null时,报错) 、strictNullChecks(需要明确处理null和undefined)

三、符号专题

0、属性  类型 【类型注解】

1、属性后面加,表示属性是可选的  function quicktest(name?:string)【可选属性】

2、多个类型用 | 分割,表示该属性可有多个类型 function quicktest(name:string | number) 【联合类型】

3、将一个值用 type name  = xxx替代,表示用name替代这个值。【类型别名】

       type name = {firstname:string}   function quicktest(name:name)

4、将一个值用 interface namet  xxx替代.【接口】//除了obj之外类型可以用吗?

      interface name {firstname:string}   

5、类型 as 更具体类型 ,把类型更具体。【类型断言】

       const dom1 = document.getElementById('canvas')  as HTMLCanvasElement

6、在某个值后面加 ! 表示明确知道某个值不是null或者undefined时

      function quicktest (name: string | null){console.log(name!.toUppercase())}

二、常见类型 - 文档笔记

1、string /number/boolean/array/any

2、变量上的类型注解  let myName:string = "Alice"; 这里类型注解不是必须的,因为ts会自动推断

如果你刚开始使用,尝试尽可能少的使用类型注解。你也许会惊讶于,TypeScript 仅仅需要很少的内容就可以完全理解将要发生的事情。

3、函数:

① 参数类型注解:跟在参数名字后面

function greet(name: string) {
  console.log("Hello, " + name.toUpperCase() + "!!");
}

②返回值类型注解:跟在参数列表后面

function getFavoriteNumber(): number {
  return 26;
}

③匿名函数参数通过上下文推断推断出s类型,会自动指定类型

4、对象类型

①列出属性和对应的类型

②可选属性:在属性后面添加一个?

function printName(obj: { first: string; last?: string }) {
  // ...
}

5、联合类型

①类型用 | 分割?

②使用时,需要用代码收窄联合类型。但如果联合类型每个成员都可应用代码则不用收窄。

function printId(id: number | string) {
  if (typeof id === "string") {
    // In this branch, id is of type 'string'
    console.log(id.toUpperCase());
  } else {
    // Here, id is of type 'number'
    console.log(id);
  }
}

6、类型别名

像赋值变量一样,将复杂或简单类型用另一个名字替代

type Point = {
  x: number;
  y: number;
};
 
// Exactly the same as the earlier example
function printCoord(pt: Point) {
  // ...
}

7、 接口

命名对象类型的另一种方式

interface Point {
  x: number;
  y: number;
}
function printCoord(pt: Point) { 
    //---
} 

类型别名和接口不同:接口可易扩展,类型别名不可扩展。

// Interface
// 通过继承扩展类型
interface Animal {
  name: string
}

interface Bear extends Animal {
  honey: boolean
}

const bear = getBear() 
bear.name
bear.honey
        
// Type
// 通过交集扩展类型
type Animal = {
  name: string
}

type Bear = Animal & { 
  honey: boolean 
}

const bear = getBear();
bear.name;
bear.honey;
// Interface
// 对一个已经存在的接口添加新的字段
interface Window {
  title: string
}

interface Window {
  ts: TypeScriptAPI
}

const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
        
// Type
// 创建后不能被改变
type Window = {
  title: string
}

type Window = {
  ts: TypeScriptAPI
}

// Error: Duplicate identifier 'Window'.

8、类型断言

将类型指定为更加具体的类型 

const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;

9、字面量类型

除了常见的string/number等类型,也可以将类型声明为一个值。常用于函数只能传入一些固定的值时。

function testFunc(name:string,gender:'male'|'female',department:'techDepart'|'manuDepart'){
   //---
}
testFunc('小米','female','techDepart') 
testFunc('小花','female','operDep') //'operDep'不在可选项 报错

①字面量推断

定义的时候给了一个字面量,使用的时候这个值来自于一个对象,就会报错

declare function handleRequest(url: string, method: "GET" | "POST"): void;

const req = { url: "https://example.com", method: "GET" };
handleRequest(req.url, req.method);

// Argument of type 'string' is not assignable to parameter of type '"GET" | "POST"'.

因为在使用req.method时,它的值'GET'会被认定为string类型。这和我们第一行声明的字面量"GET"|"POST"不同

处理方法:

方法一:添加类型断言

方法二:使用as const将整个对象转为类型字面量。对象被转为类型字面量时,默认对象中每一个属性的值都是字面量类型,而不是string/number等通用类型。

declare function handleRequest(url: string, method: "GET" | "POST"): void;

// 方法一:添加类型断言
const req = { url: "https://example.com", method: "GET" as "GET"};
// 将对象转为类型字面量
const req = { url: "https://example.com", method: "GET" } as const;

handleRequest(req.url, req.method);


10、null 或 undefined

11、非空断言 !。明确知道某个值不为null或undefined时,在其后面使用感叹号!

function liveDangerously(x?: number | null) {
  // No error
  console.log(x!.toFixed());
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值