If TypeScript is a strict superset of JavaScript, why is dot notation on an arbitrary object erroneous? I have JS code that I want to convert over to TS for better type safe
I personally prefer to specify types whenever I have the chance.
Note, that you can only instantiate this variable with {}
if you define the fields as optional with the ?:
operator.
let x: {foo?: string, bar?: string} = {};
x.foo = 'foo';
x.bar = 'bar';
As others have said, if you plan to use this type multiple times, it's probably better to make an explicit class for it.
PS: it's better to use let
instead of var
when programming in typescript. (e.g. the scope of a var
declaration is a bit quirky, compared to a let
which does what you expect it to do.)