已熟悉 JS 变量声明,下面集中看 TS 的写法和特性。
基础声明
1 2 3 4 5 6 7 8 9 10
| const siteName: string = "my-blog" let counter: number = 0
let speed = 30
let maybeId: number | undefined
|
字面量与联合类型
1 2 3 4 5 6 7
| type Theme = "light" | "dark" let theme: Theme = "light"
let id: string | number = 42 id = "user-42"
|
数组与元组
1 2 3 4 5 6 7 8 9 10
| const names: string[] = [] const scores: Array<number> = []
const position: [number, number] = [116.4, 39.9]
const readonlyTags: readonly string[] = ["ts", "notes"] const readonlyPoint: readonly [number, number] = [0, 1]
|
对象与接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const user: { id: number; name: string; readonly role?: string } = { id: 1, name: "Alice", role: "admin", }
interface User { id: number name: string role?: "admin" | "guest" }
const bob: User = { id: 2, name: "Bob" }
|
类型断言与非空断言
1 2 3 4 5 6
| const raw = JSON.parse('{"id":3,"name":"Eve"}') as User
declare const el: HTMLElement | null el!.style.display = "block"
|
其他小提示
- 尽量依赖类型推断,只有在边界和公共接口处显式标注。
- 为外部数据、接口入参写清楚类型,减少运行期错误。
- 用
readonly 防止被无意修改,用 ? 标记可选字段。