TypeScript类属性返回undefined问题咨询及输出指定内容方法
t.test Returns undefined & How to Fix It Hey there, let's unpack this issue clearly—you're hitting a classic gotcha with TypeScript's type annotations vs. runtime values.
The Root Cause
Your code class T { test: "print me" } only adds a type annotation to the test property, not an actual runtime value.
TypeScript is a static type checker, so all type information gets stripped out when it compiles to JavaScript. The resulting JS code looks like this:
class T {} const t = new T(); document.write(t.test);
Since the T class has no test property defined or initialized, accessing t.test naturally returns undefined.
How to Correctly Output "print me"
You need to initialize the test property so it exists at runtime. Here are a few clean ways to do this:
1. Direct In-Class Initialization
This is the simplest approach—assign the value right where you declare the property. You can even omit the explicit type annotation since TypeScript will infer it from the value:
class T { test = "print me"; // TypeScript infers type as "print me" automatically } const t = new T(); document.write(t.test); // Outputs "print me"
If you want to keep the explicit type (for clarity or stricter checks), you can write:
class T { test: "print me" = "print me"; }
2. Initialize in the Constructor
If you need to compute the value dynamically, use the constructor:
class T { test: "print me"; constructor() { this.test = "print me"; } } const t = new T(); document.write(t.test);
3. Parameter Property (Shorthand)
For a more concise syntax, use TypeScript's parameter property feature to declare and initialize the property in one line:
class T { constructor(public test: "print me" = "print me") {} } const t = new T(); document.write(t.test);
Common Scenarios Where TypeScript Properties Return undefined
This issue isn't unique to your code—here are other frequent cases where you might encounter an undefined property:
- Optional properties: If you mark a property with
?(e.g.,test?: string), it's allowed to beundefinedif not initialized. - Missing initialization in strict mode off: When TypeScript's
strictPropertyInitializationis disabled, you can declare a non-optional property without initializing it, leading toundefinedat runtime. declared properties: Usingdeclare(e.g.,declare const test: string) tells TypeScript the property exists, but it doesn't add it to the runtime code—so accessing it will beundefinedif it's not actually defined elsewhere.- Inheritance gaps: If a parent class declares a property without initializing it, and the child class doesn't set it either, the instance will have an
undefinedproperty.
The core takeaway here is: TypeScript type annotations don't create runtime values—you always need to explicitly initialize properties if you want them to exist when your code runs.
内容的提问来源于stack exchange,提问作者NoKey

