typescript - Declaring type based on variable -


in typescript, can have variable implicitly typed based on variable.

var json = {foo: 1}; var sometypedvariable = json; // assignment gives implicit type  sometypedvariable.bar = 1; // error sometypedvariable.foo = 1; // 

but there way achieve same result without assigning? know can do:

var sometypedvariable: {foo:number}; 

but like:

var json = {foo: 1}; var sometypedvariable: json; // explicitly typing without assignment 

is there way achieve this?

why trying this? have large json structures type checking on. it's easy throw sample data in ts file, , when assign data variable, type checking on variable. don't want maintain class structure json - want able (when json structure changes) copy/paste new json file project , see if of dependent code breaks.

sure, there way! the related proposal of type queries implemented:

var json = {foo: 1}; var sometypedvariable : typeof json; // type query, not string "object"  sometypedvariable.bar = 1; // error sometypedvariable.foo = 1; // 

one thing note typeof operator in context of type expression type query, , doesn't mean same typeof in simple expression.

you can try in typescript playground.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo