TypeScript类初始化报错:私有变量缺失的原因咨询
myClass Array with Object Literals? Great question! Let's break down why TypeScript is throwing that error and how to fix it properly.
The Root Cause
When you define a class like myClass, TypeScript’s type system treats every instance of the class as having all declared properties—including private ones—no matter their access modifier. Your object literals { aVariable: 3 } and { aVariable: 2 } only include the public aVariable property, but they’re missing the private aPrivateVariable that’s a required part of the myClass type.
TypeScript enforces this because even though private properties aren’t accessible from outside the class, they’re still part of the instance’s underlying structure. The type checker makes sure anything claiming to be a myClass instance has all the properties the class defines.
Why Object Literals Can’t Mimic Class Instances
You might wonder, "What if I just add aPrivateVariable to the object literal?" But private properties are scoped exclusively to the class itself—TypeScript won’t let you set or reference them from outside the class definition. Even if you tried:
// This will still fail! let someVar: myClass[] = [{ aVariable: 3, aPrivateVariable: 5 }, ...];
You’d get an error saying 'aPrivateVariable' is private in type 'myClass' but not in type '{ aVariable: number; aPrivateVariable: number; }'. That’s because private properties create a unique "type brand" for the class, preventing plain object literals from being treated as valid class instances.
The Correct Initialization Approach
To create valid myClass instances, you need to use the new keyword with the class constructor. This ensures each instance gets all the properties (including private ones) defined by the class:
let someVar: myClass[] = [new myClass(3), new myClass(2)];
Quick note: Your current myClass declares aPrivateVariable as a number but doesn’t initialize it. To avoid runtime issues, you should set a default value or initialize it in the constructor, like this:
export class myClass { constructor(public aVariable: number) {} private aPrivateVariable: number = 0; // Add a default value }
内容的提问来源于stack exchange,提问作者Michael Witt

