我正在寻找将一个对象映射到一个类,也许我的技术措辞是错误的,所以我会试着说明。
var car = {wheels:4, color:"red", maxSpeed: 100}
class Car(){
wheels: number;
color: string;
maxSpeed: number
}
let wrappedCar = new Car(**car)
console.log(wrappedCar.wheels)
// 4
在Typescript中实现这一目标的最佳方法是什么? :)
答案 0 :(得分:2)
这对你好吗?
var car = { wheels: 4, color: "red", maxSpeed: 100 }
class Car {
wheels: number;
color: string;
maxSpeed: number
}
let wrappedCar = <Car> car
console.log(wrappedCar.wheels)
执行此操作的正确解决方案是使用构造函数并合并对象:
var car = { wheels: 4, color: "red", maxSpeed: 100 }
class Car {
wheels: number;
color: string;
maxSpeed: number
constructor(carObj) {
for (var a in carObj) { this[a] = carObj[a] }
}
}
let wrappedCar = new Car(car)
console.log(wrappedCar.wheels)
答案 1 :(得分:1)
如果你需要做的就是描述一个对象结构,你可以使用界面。
就像这样
interface Car {
wheels: number;
color: string;
maxSpeed: number
}
稍后您可以正常使用它。
let car: Car = {
wheels: 4,
color: "red",
maxSpeed: 100
}
编译器还将自动识别对象是否实现了该接口。因此,它非常适合描述您希望在方法中获得的内容。
function washCar(car: Car): void {}
washCar({
wheels: 10,
color: 'red',
maxSpeed: 100
}); // will work
washCar({
name: 'John',
age: 5
}); // will generate a compilation error