原始类型:
string、number、boolean
const name: string = 'Alice'
const age: number = 18
const student: boolean = true
泛型
Arrays: number[]、string[]
const classmates: string[] = ['Lily', 'Mark', 'Villiam'] // 等价于 Array<string>
const classmates_ages: number[] = [18, 19, 18] // 等价于 Array<number>
特殊类型
any
let obj: any = {x: 0}
obj.foo = () => {}
{
"compilerOptions": {
"noImplicitAny": true // 禁止使用隐式 any 类型
}
}
函数类型
Function:
- 参数
- 返回值
// 参数:基础类型 无返回值
function sayHello(name: string):void {
console.log(`Hello~ ${name}.`)
}
// 返回值:原始类型
function userAge(): number {
return 18
}
// 返回值: Promise
async function getUserAge(): Promise<number> {
return 18;
}
对象类型
// 对象类型
function students(obj: {name: string, age: number}) {
// ...
}
// 对象类型: 可选属性
function studentFamily(obj: {name: string, age: number, relationship?: string}) {
if(obj.relationship !== undefined) { // 等价于 console.log(obj.relationship?.toUpperCase())
// 可选类型在使用时,需要先做判断
console.log(obj.relationship.toUpperCase())
}
}
联合类型
function studentFamily(family: string[] | string) {
if(Array.isArray(family)) {
console.log(family.join(' and '))
} else {
console.log(family)
}
}
类型别名
type StudentId = number | string
type StudentFamily = {
name: string
age: number
relationship?: string
}
function getFamilyByUserId(id: StudentId): StudentFamily {
// ...
return {
name: 'Mark White',
age: 50,
relationship: 'parent'
}
}
接口
interface StudentFamily {
name: string
age: number
relationship?: string
}
function updateFamily(family: StudentFamily) {
// ...
}
接口扩展 vs 类型扩展
类型断言
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
// 等价于 (除了 .tsx 文件)
const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");
字面类型
type Position = 'Top' | 'Bottom' | 'Left' | 'Right'
type Numberic = 0 | 1
type Bool = true | false
function doAction(position: Position | 'Center', times: Numberic | Bool) {
// ...
}
字面推断
declare function handleRequest(url: string, method: "GET" | "POST"): void
// 写法一
const req = { url: "https://example.com", method: "GET" };
handleRequest(req.url, req.method as "GET");
// 写法二
const req = { url: "https://example.com", method: "GET" as "GET" };
handleRequest(req.url, req.method as "GET");
// 写法三
const req = { url: "https://example.com", method: "GET" } as const;
handleRequest(req.url, req.method);
null & undefined
{
"compilerOptions": {
"strictNullChecks": true // 需要严格检查 null 和 undefined
}
}
function doSomething(value: string | null) {
if(value === null) {
// ...
} else {
// ...
}
}
其他不常用类型
原始类型 bigint
const anotherHundred: bigint = 100n;
原始类型 symbol
const uniqSym = Symbol(1)
const compareSym = Symbol(1)
if(uniqSym === compareSym) {
// never happen...
}