0

Please see the code here

interface ITest {
    Name: string
}

var t:ITest;
//var t:ITest = {Name:null};

t.Name = "hello";

this is a runtime error as t never initialized, and can solve by uncommenting the line. Is there a way to detect assignment to un-initialized variable at compile time?

2 Answers 2

1

No, there isn't a standardized way in TypeScript to prevent assignment to a property of an un-initialized variable.

Many would try to catch that error through a unit test or an assertion library that would verify the object exists before setting the property.

Sign up to request clarification or add additional context in comments.

Comments

1

No TS can't do that. For good reason. Say you declare in file a, setup in file b and use in file c.

TypeScript can't know that you are going to load file a then b then c. At runtime you might end up loading files c first (using a script tag) and will still get this error.

1 Comment

While it's true that there are cases where it couldn't work, there certainly are cases where it could.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.