JavaScript 的超集 - 带类型的 JavaScript
// 基础类型
let count: number = 42
let name: string = "TypeScript"
let isActive: boolean = true
// 数组
let numbers: number[] = [1, 2, 3]
let names: Array = ["A", "B"]
// 元组
let user: [string, number] = ["Alice", 25]
// 枚举
enum Color {
Red = "red",
Green = "green",
Blue = "blue"
}
// 任意类型
let anything: any = 4
anything = "four"
类型检查结果:
数字: 42
字符串: TypeScript
布尔值: true
interface User {
id: number
name: string
email?: string // 可选属性
readonly age: number // 只读属性
}
interface Admin extends User {
role: 'admin' | 'super-admin'
}
function createUser(user: User): User {
return user
}
const admin: Admin = {
id: 1,
name: "Alice",
age: 25,
role: "admin"
}
interface Calculator {
(a: number, b: number): number
}
const add: Calculator = (a, b) => a + b
const multiply: Calculator = (a, b) => a * b
interface Config {
name: string
version: string
config(options: Config): void
}
const appConfig: Config = {
name: "MyApp",
version: "1.0.0",
config(options) {
console.log(options)
}
}
class Person {
name: string
age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
greet(): string {
return `Hello, I'm ${this.name}`
}
}
class Employee extends Person {
employeeId: number
department: string
constructor(
name: string,
age: number,
id: number,
dept: string
) {
super(name, age)
this.employeeId = id
this.department = dept
}
greet(): string {
return `${super.greet()}, ID: ${this.employeeId}`
}
getInfo(): string {
return `${this.name}, ${this.age}, Dept: ${this.department}`
}
}
function identity<T>(arg: T): T {
return arg
}
let stringResult = identity<string>("hello")
let numberResult = identity<number>(42)
// 泛型约束
interface Lengthwise {
length: number
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length)
return arg
}
class GenericNumber<T> {
value: T
constructor(value: T) {
this.value = value
}
add(another: T): T {
return this.value + another
}
}
let numberGeneric = new GenericNumber<number>(10)
let stringGeneric = new GenericNumber<string>("Hello ")
let id: number | string
id = "abc123"
id = 123
function printId(id: number | string) {
console.log(id)
}
interface Person {
name: string
}
interface Employee {
employeeId: number
}
type PersonEmployee = Person & Employee