基础类型
let a: string
let a: number
let 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属性被自动推断为string
handleRequest(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 2
handleRequest(req.url, req.method as "GET");
const req = { url: "https://example.com", method: "GET" } as const;
handleRequest(req.url, req.method);
null undefined
strictNullChecks off
null undefined 可以赋值给任意类型
strictNullChecks on (推荐打开)
只能赋值给他自己的类型
使用 ! 可以告诉ts该值不为空或未定义
function liveDangerously(x: number | null) {
console.log(x!.toFixed());
}
不常见的类型
let one: bigint = BigInt(1)
const a = Symbol('name')