Skip to content

ts教程

强类型声明

  • 字段声明
ts
let name: string = '张三'     // 明确标注为字符串
let age: number = 25         // 明确标注为数字
let isStudent: boolean = true // 明确标注为布尔值
let hobbies: string[] = ['篮球', '音乐'] // 字符串数组
  • 定义对象类型
ts
interface User {
  name: string
  age: number
  email: string
}

const user: User = {
  name: '李四',
  age: 30,
  email: 'lisi@example.com'
}

count?: number // 可选属性
  • 定义函数类型
ts
interface Add {
  (a: number, b: number): number
}
const add: Add = (a, b) => {
  return a + b
}

vue + ts

ts
// ref - 需要指定类型
const count = ref<number>(0)
const name = ref<string>('张三')

// reactive - 通过接口定义类型
interface User {
  name: string
  age: number
  email?: string
}
const user = reactive<User>({
  name: '张三',
  age: 25
})

// 定义数组类型
interface Product {
  id: number
  name: string
  price: number
  category: string
}

const products = ref<Product[]>([]) // 产品列表
const loading = ref<boolean>(false) // 加载状态

// 定义后端返回的数据类型
interface ApiResponse<T> {
  code: number
  message: string
  data: T
}
interface User {
  id: number
  name: string
  email: string
}
// 使用
const userData = ref<ApiResponse<User>>()

函数没有返回值

ts
// 在后面加入 : void 
function sayHello(): void {
  console.log('Hello, world!')
}