基础类型
let a: stringlet a: numberlet a: boolean
数组
let a: number[]let a: Array<number>
any
let a: any
函数
function a (name: string): number {}
对象
let pos: {x: number,y?: number}
联合类型
let a: string | number
类型别名
type Position = { x: number, y?: number}type Id = string | number
接口
interface Person { name: string, age?: number}
类型与接口的不同
接口扩展interface Person { name: string}interface Student extends Person { age: number}类型扩展type Person = { name: string}type Student = Person & { age: number}接口修改,创建后可以直接修改interface Person { name: string}interface Person { age: number}类型修改,创建后不能修改type Person = { name: string}type Person = { age: number 报错}
断言
const cnavas = document.getElementById('canvas') as HTMLCanvasElement在tsx中会引起混淆,推荐用第一种const cnavas = <HTMLCanvasElement>document.getElementById('canvas')
文字类型
let s: 'hello's = 'world' 报错或者直接用const用处type Direction = "left" | "right" | "center"let a: Direction = 'cneter' 因为拼写不对,报错数字类型type Val = 0 | 1跟其他类型合并interface Options { width: number;}function configure(x: Options | "auto") { // ...}configure({ width: 100 });configure("auto");configure("automatic"); 报错
自动推断
let o = { name: '李狗蛋'}o.name = 11 报错
const req = { url: "https://example.com", method: "GET" }; 因为在定义对象时,method属性被自动推断为stringhandleRequest(req.url, req.method); 报错 string 不能赋值给 "GET" | "POST"handleRequest(req.url, "GET");function handleRequest (url:string, method: "GET" | "POST"): void {}
// Change 1:const req = { url: "https://example.com", method: "GET" as "GET" };// Change 2handleRequest(req.url, req.method as "GET");
const req = { url: "https://example.com", method: "GET" } as const;handleRequest(req.url, req.method);
null undefined
strictNullChecks offnull undefined 可以赋值给任意类型strictNullChecks on (推荐打开)只能赋值给他自己的类型
使用 ! 可以告诉ts该值不为空或未定义function liveDangerously(x: number | null) { console.log(x!.toFixed());}
不常见的类型
let one: bigint = BigInt(1)const a = Symbol('name')