2

How to check null on interface variable and how to set the default value in typescript?

const userModel = snap.data() as UserModel //firestore

export interface UserModel {
    docId: string, 
    accountId: number // if null then I want to set 0
}

Sometimes, users don't have the account id. So how do I check it?

if (userModel.userPushToken !== undefined) - Currently I am checking like this

BIS Tech
  • 17,000
  • 12
  • 99
  • 148

2 Answers2

6

Initializers in interfaces

In Typescript an interface is only a description of how an object should look and can't contain any functions. Because of this you don't have to construct an interface like you would need to do with a class. And because of this you are not able to do any initialization in the interface.
If you compile a typescript interface to javascript, the typescript compiler just deletes it, because it has no functionality except to make things more readable and provide type checking.
If you want to initialize a variable I would recommend you to change the interface to a class:

export class MyUserModel implements UserModel{
    public docId: string;
    public accountId: number

    constructor(usrmodel:UserModel){
        this.docId = usrmodel.docId || ""; // Initialize with "" if docId is null or undefined
        this.accountId = usrmodel.accountId || 0; // Initialize with 0 if accountid is null or undefined
    }
}

or write a "copy-constructor" for the interface:

function InitUserModel(usrModel:UserModel):UserModel{
    usrModel.accountId = usrModel.accountId || 0;
    return usrModel;
}

Check if null or undefined

There are a lot of good posts for this. For example Is there a way to check for both `null` and `undefined`?

1

Typescript is just type.

So, You can not set default value.

But, You can set default type.

export interface UserModel<T> {
    docId: string, 
    accountId: T extends number ? number : 0 // if null then I want to set 0
}


const snap: any = {}

const userModel = snap.data() as UserModel<void> //firestore

userModel.accountId = 0 // if assign not 0, error occured.

You can set default value in function.

But, It it javascript not typescript.

type Params = {
    a: number,
    b: string
}

const foo = ({ a=1, b='something'}: Params ) => {
    console.log(params);
}
hyundeock
  • 445
  • 1
  • 6
  • 15