In TypeScript, I can do something like this to have a variable implicitly typed based on another variable.
var json = {foo: 1};
var someTypedVariable = json; // Assignment gives implicit type
someTypedVariable.bar = 1; // Error
someTypedVariable.foo = 1; // Good
But is there any way to achieve the same result without assigning? I know I can do:
var someTypedVariable: {foo:number};
But what about something like:
var json = {foo: 1};
var someTypedVariable: json; // Explicitly typing without assignment
Is there any way to achieve this?
Why am I trying to do this? I have some large JSON structures that I would like type checking on. It's easy to throw the sample data in a ts file, and when I assign that data to a variable, I get type checking on that variable. I don't want to maintain a class structure for the JSON - I just want to be able to (when the JSON structure changes) copy/paste the new JSON file into my project and see if any of my dependent code breaks.
Sure, there is a way! As the related proposal of type queries is already implemented:
var json = {foo: 1};
var someTypedVariable : typeof json; // type query, not the string "object"
someTypedVariable.bar = 1; // Error
someTypedVariable.foo = 1; // Good
One thing to note is that the typeof operator in the context of a type expression is a type query, and doesn't mean the same as typeof in a simple expression.
You can try it in the TypeScript playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With