如何在接口变量上检查null以及如何在typescript中设置默认值?
const userModel = snap.data() as UserModel //firestore
export interface UserModel {
docId: string,
accountId: number // if null then I want to set 0
}
有时,用户没有帐户id。那么我该如何检查呢?
if (userModel.userPushToken !== undefined)
-目前我正在像这个一样检查
接口中的初始化器
在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
}
}
或者写一个";复制构造函数";对于接口:
function InitUserModel(usrModel:UserModel):UserModel{
usrModel.accountId = usrModel.accountId || 0;
return usrModel;
}
检查是否为null或未定义
有很多好的帖子。例如,有没有办法同时检查"null"one_answers"undefined"?
Typescript只是类型。
因此,您不能设置默认值。
但是,您可以设置默认类型。
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.
您可以在函数中设置默认值。
但是,它是javascript而不是typescript。
type Params = {
a: number,
b: string
}
const foo = ({ a=1, b='something'}: Params ) => {
console.log(params);
}