4

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?

3
  • 2
    Writing var myType: IMyType | null is the correct way to make it nullable. When it can be null in 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 elsewhere Commented Oct 25, 2021 at 7:35
  • 1
    You can use a more readable version of it like this type Nullable<T> = T | null; and define your variable like this var myType: Nullable<IMyType> = null Commented Oct 25, 2021 at 7:54
  • I think there is a tslint option to allow this. My Angular project allows this at least, but I don't know what configuration is responsible for allowing it. Commented Oct 25, 2021 at 8:20

1 Answer 1

6

In addition to my comment, here is a minimal working example.

When a field is nullable, it's type will be MyType | null. If you want to get rid of the null part, you can either check for null or cast it to the non-nullable type. Casting however is risky because the casted variable might still be null.

Or put the null-check inline with ?? and specify the value in case of null.

interface IMyType {
  foo: string, 
  bar?: string,
}

var somethingNotNull: IMyType = {foo: 'foo', bar: 'bar'};

var nullableMyType: IMyType | null = null;

const shouldNotBeNull = false;
if (shouldNotBeNull) {
  nullableMyType = somethingNotNull;
}

var casted: IMyType = nullableMyType as IMyType; // dangerous because casted pretends to be not nullable, but still might be null if myType is null

// var notNull: IMyType = myType; // does not compile: Type 'IMyType | null' is not assignable to type 'IMyType'

if (nullableMyType !== null) {
  var notNull: IMyType = nullableMyType; // does compile
}

var notNull: IMyType = nullableMyType ?? {foo: '', bar: ''}; // Specify value for the null case
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.