I was testing some code that utilizes objects in TypeScript and noticed that my IDE's IntelliSense was throwing an error for a new property I was trying to add. It states that the property "text" does not exist, here is my code:
// create new object
var thing : Object = new Object();
// Do things
thing.text = "This is a test.";
console.log(thing.text);
// dereference the object
thing = null;
The error is highlighted on the line(s):
thing.text = "This is a test.";
console.log(thing.text);
Why does VS code list this as an error when this is perfectly acceptable code and behavior in JavaScript? Here is the error screenshot from my editor: Error
EDIT: I should note the code does compile into valid JS with tsc and runs just fine, just curious why the error is showing up as it throws me off while writing the code and makes me think there is some problem when there is not. It also notes in tsc's output the same errors, does this language behavior of being able to add and remove properties to objects change from JavaScript to TypeScript?
CodePudding user response:
Typescript types are not part of your final code. When you build/run your code, there are no types. They're just there for your benefit when programming. So you can write valid code with incorrect types. Typescript will complain, but your code will still run.
When you initialize your variable, you're setting its type to Object
. Which is basically {}
. It doesn't have any properties. When you try to set a value for thing.text
it gives you an error because thing
doesn't have any properties.
You have a couple options:
- Initialize
thing
withtext
:
const thing = { text: "This is a test." };
thing.text = "You can change the value if you want.";
console.log(thing.text);
Note, you don't need to define the type of thing
. Typescript knows its type by its value.
- Or, Declare a type for
thing
wheretext
is optional:
type ThingType = {
text?: string;
};
// or just: const thing: ThingType = {}
const thing: ThingType = new Object();
thing.text = "This is a test.";
console.log(thing.text);