意图驱动编程(Intent-Driven Programming)
2025/12/26 13:47:05
TypeScript对象可以被视为包含一组键值对的实例。
TypeScript映射实体时,一般将:
(1) 实体的特征、状态转为属性。
(2) 行为、功能转为函数。
TypeScript创建对象的方法一般有以下几种:
(1) 字面方式创建对象,在定义结构的同时创建对象
(2)直接创建匿名对象
(3)使用接口定义结构并创建对象
(4)用类的构造方法创建对象
const person={ name:'张三', age:18, birthday:'2003-10-18', hobbies:['篮球','足球'], sayHello:function(){ console.log(`hello,${this.name}`); }, printfInfo:function(){ console.log(`姓名:${this.name},年龄:${this.age}`); console.log(`爱好:${this.hobbies}`); console.log(`生日:${this.birthday}`); } } console.log(person.sayHello()); console.log(person.printfInfo());function greet(person: { name: string; age: number }) { return "Hello " + person.name; } console.log(greet({ name: "Bob", age: 25 }));通过 interface 关键字,我们可以给对象类型命名,使其可以在多个地方复用。
interface Person { name: string; age: number; hobbies: string[]; } const person: Person = { name: "Alice", age: 30, hobbies: ["reading", "swimming"] }; console.log(person.hobbies);class Person { name: string; age: number; hobbies: string[]; constructor(name: string, age: number) { this.name = name; this.age = age; this.hobbies = []; } sayHello() { console.log(`hello,${this.name}`); } printfInfo() { console.log(`姓名:${this.name},年龄:${this.age}`); console.log(`爱好:${this.hobbies}`); } addHobby(hobby: string) { this.hobbies.push(hobby); } } const person1 = new Person("张三", 18); person1.addHobby('篮球'); person1.addHobby('足球'); person1.printfInfo();