Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring type based on variable

Tags:

typescript

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.

like image 907
Eric Avatar asked Jun 16 '26 11:06

Eric


1 Answers

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.

like image 160
Tamas Hegedus Avatar answered Jun 19 '26 04:06

Tamas Hegedus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!