接口用于定义对象的类型结构,确保对象具有正确的属性和方法。
interface User {
id: number
name: string
email: string
}
interface User {
id: number
name: string
email: string
}
const user: User = {
id: 1,
name: "张三",
email: "zhangsan@example.com"
}
function greet(user: User): string {
return `你好,${user.name}`
}
greet({ id: 1, name: "张三", email: "zhangsan@example.com" })
function createUser(name: string, email: string): User {
return {
id: Date.now(),
name,
email
}
}
interface User {
id: number
name: string
email: string
}
const user: User = {
id: 1,
name: "张三"
// 错误:缺少 email 属性
}
interface User {
id: number
name: string
}
const user: User = {
id: 1,
name: "张三",
age: 25 // 错误:多余的属性
}
使用类型断言绕过多余属性检查:
const user = {
id: 1,
name: "张三",
age: 25
} as User
interface Calculator {
add(a: number, b: number): number
subtract(a: number, b: number): number
}
const calc: Calculator = {
add(a, b) {
return a + b
},
subtract(a, b) {
return a - b
}
}
interface Calculator {
add: (a: number, b: number) => number
subtract: (a: number, b: number) => number
}
interface ApiResponse<T> {
code: number
message: string
data: T
}
interface User {
id: number
name: string
}
async function fetchUser(id: number): Promise<ApiResponse<User>> {
const response = await fetch(`/api/users/${id}`)
return response.json()
}
interface ServerConfig {
host: string
port: number
ssl?: boolean
}
function createServer(config: ServerConfig): void {
const protocol = config.ssl ? "https" : "http"
console.log(`服务器启动: ${protocol}://${config.host}:${config.port}`)
}
createServer({ host: "localhost", port: 3000 })
interface LoginForm {
username: string
password: string
rememberMe?: boolean
}
function submitForm(data: LoginForm): Promise<void> {
return fetch("/api/login", {
method: "POST",
body: JSON.stringify(data)
})
}
同名接口会自动合并:
interface User {
name: string
}
interface User {
age: number
}
const user: User = {
name: "张三",
age: 25
}
TypeScript 使用结构化类型系统:
interface Point {
x: number
y: number
}
function printPoint(point: Point): void {
console.log(`(${point.x}, ${point.y})`)
}
const point = { x: 10, y: 20, z: 30 }
printPoint(point) // 正确:只要包含 x 和 y 就可以
直接传字面量会进行严格检查:
interface User {
name: string
}
function printUser(user: User): void {
console.log(user.name)
}
printUser({ name: "张三", age: 25 }) // 错误:多余属性
const user = { name: "张三", age: 25 }
printUser(user) // 正确:变量赋值不检查多余属性