在TypeScript中为实例赋值有多种方式,具体取决于实例的类型和需求。以下是几种常见的方式:
class Person {
name: string;
age: number;
}
const person = new Person();
person.name = "John";
person.age = 25;
class Person {
constructor(public name: string, public age: number) {}
}
const person = new Person("John", 25);
class Person {
name: string;
age: number;
}
const data = { name: "John", age: 25 };
const person = new Person();
({ name: person.name, age: person.age } = data);
class Person {
name: string;
age: number;
}
const data = { name: "John", age: 25 };
const person = new Person();
Object.assign(person, data);
这些方法可以根据实际情况选择使用,根据实例的类型和需求来决定最适合的赋值方式。
领取专属 10元无门槛券
手把手带您无忧上云