user1283776
user1283776

Reputation: 21814

How to handle objects that can be null in Typescript?

I want a function to return either an object or null.

Here is how I handle it today:

export interface MyObject {
    id: string
}

function test(id) : MyObject | null {
    if (!id) {
        return null;
    }

    return {
        id: id
    }
}

Is this best practice?

I would prefer to make the interface nullable rather than returning MyObject | null.

But I don't know if that is possible.

Upvotes: 2

Views: 3157

Answers (3)

Paleo
Paleo

Reputation: 23762

Is this best practice?

It's just fine. Everybody does that (or with undefined).

I would prefer to make the interface nullable rather than returning MyObject | null.

You can do:

export type NullableObject = null | {
  id: string
}

It is uncommon but fine too.

Upvotes: 2

Jonas Høgh
Jonas Høgh

Reputation: 10884

In Typescript, null and undefined are part of the domains of all types, unless strict null checks are enabled. In my opinion, explicitly declaring nulls is a much better practice than having them everywhere implicitly, but in the real world it is often not realistic to enable strict mode when interoperating with library code that isn't designed for it.

Upvotes: 1

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92677

This should handle null case too (if --strictFunctionTypes compiler option is off)

function test(id) : MyObject {
    if (!id) {
        return null;
    }

    return {
        id: id
    }
}

Upvotes: 0

Related Questions