typescript 接口变量 null 检查并设置默认值

Blo*_*oss 2 firebase typescript google-cloud-functions

如何检查接口变量上的 null 以及如何在打字稿中设置默认值?

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

export interface UserModel {
    docId: string, 
    accountId: number // if null then I want to set 0
}
Run Code Online (Sandbox Code Playgroud)

有时,用户没有帐户 ID。那么我该如何检查呢?

if (userModel.userPushToken !== undefined)- 目前我正在这样检查

小智 6

接口中的初始化器

在 Typescript 中,接口只是对象外观的描述,不能包含任何函数。因此,您不必像使用类那样构造接口。因此,您无法在界面中进行任何初始化。
如果您将 Typescript 接口编译为 JavaScript,TypeScript 编译器只会将其删除,因为它除了使内容更具可读性并提供类型检查之外没有任何功能。
如果您想初始化变量,我建议您将接口更改为类:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

或者为接口编写一个“复制构造函数”:

function InitUserModel(usrModel:UserModel):UserModel{
    usrModel.accountId = usrModel.accountId || 0;
    return usrModel;
}
Run Code Online (Sandbox Code Playgroud)

检查是否为空或未定义

有很多这方面的好帖子。例如,有没有办法检查“null”和“undefined”?