TypeScript 中声明变量并指定类型的常用方法
·
1. 基本变量类型声明
// 直接声明类型
let name: string = "hello"
let age: number = 18
let isActive: boolean = true
let items: string[] = []
let user: { name: string; age: number } = { name: "Tom", age: 25 }
2. 使用泛型声明 Ref 类型
// 显式指定泛型类型参数(最推荐)
const result = ref<string[]>([])
// 或者声明 Ref 类型变量
const result: Ref<string[]> = ref([])
3. 接口和类型别名
// 使用 interface 定义对象类型
interface User {
name: string
age: number
}
const user: User = { name: "Tom", age: 25 }
// 使用 type 定义类型别名
type UserRole = 'admin' | 'user' | 'guest'
const role: UserRole = 'admin'
4. 联合类型和可选类型
// 联合类型
let value: string | number = "text"
value = 123
// 可选属性
interface Config {
timeout?: number
retries?: number
}
const config: Config = {}
5. 函数类型声明
// 函数参数和返回值类型
function add(a: number, b: number): number {
return a + b
}
// 箭头函数类型声明
const multiply: (a: number, b: number) => number = (a, b) => a * b
// 使用类型别名定义函数类型
type MathOperation = (a: number, b: number) => number
const subtract: MathOperation = (a, b) => a - b
6. 泛型类型
// 泛型函数
function identity<T>(arg: T): T {
return arg
}
// 泛型接口
interface GenericIdentityFn<T> {
(arg: T): T
}
// 使用泛型
const stringResult = identity<string>("hello")
const numberResult = identity<number>(42)
7. 类型断言
// 使用 as 关键字
const someValue: any = "this is a string"
const strLength: number = (someValue as string).length
// 使用尖括号语法(在 JSX 中不适用)
const strLength2: number = (<string>someValue).length
8. 数组和元组类型
// 数组类型声明
let list1: number[] = [1, 2, 3]
let list2: Array<string> = ["a", "b", "c"]
// 元组类型
let tuple: [string, number] = ["hello", 10]
9. 枚举类型
// 数字枚举
enum Direction {
Up,
Down,
Left,
Right
}
// 字符串枚举
enum HttpStatus {
OK = "200",
NotFound = "404",
Error = "500"
}
const direction: Direction = Direction.Up
更多推荐



所有评论(0)