简体   繁体   English

具有私有属性的Typescript对象转换

[英]Typescript Object casting with private properties

i am trying to cast an object into a specific class but i get the error that "_myPropertyPriv is Missing in type ClassA" 我试图将对象转换为特定的类,但出现错误“ ClassA类型缺少_myPropertyPriv”

class ClassA{
    MyPropertyPub:number;
    private _myPropertyPriv
}
**later
var obj:ClassA = { MyPropertyPub:3 };

The reason i dont use a constructor is because in the real class i have theirs 20 ish properties and i dont want a constructor with that many properties. 我不使用构造函数的原因是,在真实的类中,我拥有20种属性,并且我不希望构造器具有这么多的属性。

There is a reason typescript does not allow this: 有一个原因是打字稿不允许这样做:

class ClassA{
    MyPropertyPub:number;
    private _myPropertyPriv;
    public method() {

    }

}
var obj:ClassA = <any>{ MyPropertyPub:3 }; //works
obj.method();; // runtime error, obj is not actually of type ClassA

Typescript provides the Partial type to define a type that contains a subset of the members of the original class : Typescript提供了Partial类型来定义一个类型,该类型包含原始类的成员的子集:

var obj2:Partial<ClassA>= { MyPropertyPub:3 };

Also creating a constructor for the class using Partial and Object.assign is trivial and very useful: 使用Partial和Object.assign为类创建构造函数也是很简单且非常有用的:

class ClassA{
    MyPropertyPub:number;
    private _myPropertyPriv;

    constructor(cfg: Partial<ClassA>){
        Object.assign(this, cfg);
    }
    public method() {

    }
}

var obj3 = new ClassA({
    MyPropertyPub: 10
});
obj3.method();

There's no casting present in your question. 您的问题中没有强制性规定。 You can use a type assertion (commonly referred to as a cast) to do this: 您可以使用类型断言(通常称为强制类型转换)来执行此操作:

var obj:ClassA = { MyPropertyPub:3 } as ClassA; // OK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM