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.