Suppose I have a custom class;
interface IMyType {
foo: string
bar?: IChild
}
Now I want to optionally instantiate that type:
var myType: IMyType = null
if (something) { myType = somethingNotNull }
This results in;
TS2322: Type 'null' is not assignable to type 'IMyType'.
So now I can do this:
var myType: IMyType | null = null
And that seems to work, but now I've got my optionals declared using "?" in the class declaration, and using "| null" elsewhere, which seems really ugly/messy/incorrect. What's the correct way to achieve consistent optional behaviour in typescript?
var myType: IMyType | nullis the correct way to make it nullable. When it can benullin another place as well, it has to be declared the same way there. You can make null check though to get rid of the nullable type elsewheretype Nullable<T> = T | null;and define your variable like thisvar myType: Nullable<IMyType> = null