[英]How to initialize a typescript class from existing object?
This may be looking similar to previous questions, but I didn't find my answer, so I asked it here.这可能看起来与以前的问题相似,但我没有找到答案,所以我在这里问了。 My example:我的例子:
Class A{
id:number;
name:string;
}
Class B{
id:number;
name:string;
age:number;
grade:number;
}
const b = new B {id:1, name:'John', age: 20, grade: 10}
Now I want to initialize a new instance of class A only with two attributes from class B. Something like this:现在我想用 class B 的两个属性初始化 class A 的新实例。像这样:
const a = b as A;
I need my result look like this:我需要我的结果如下所示:
a = {id:1, name:'John'}
Thanks,谢谢,
class A {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
static toA<T extends { id: number, name: string }>({ id, name }: T): A {
const newObject = new A(id, name);
return newObject;
}
}
It is not possible to change the runtime structure by only cheating TypeScript.仅作弊 TypeScript 是无法改变运行时结构的。 as
just tells TypeScript "Don't think too much, just assume b
as A
," and TypeScript won't do anything (including writing a B to A converter for you) except assuming the type of that object is A
in the type-checking (compile) time. as
A 告诉 TypeScript “不要想太多,假设b
为A
”,并且 TypeScript 不会做任何事情(包括为您编写 B 到 A 转换器),除非假设 ZA8CFDE6311BD59EB2AC96F 中A
类型为 is检查(编译)时间。
So, We should write an explicit converter for it.所以,我们应该为它写一个显式的转换器。 We received any object with the required fields, then create a new A
object with those fields.我们收到了任何包含必填字段的 object,然后使用这些字段创建一个新A
object。
class A {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
static toA<T extends { id: number, name: string }>({ id, name }: T): A {
const newObject = new A(id, name);
return newObject;
}
}
class B extends A {
test: number;
constructor(id: number, name: string, test: number) {
super(id, name);
this.test = test;
}
}
const b = new B(1, "hi", 2);
console.log(A.toA(b)); // A { id: 1, name: 'hi' }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.