[英]Javascript function without curly braces
一個好的 function聲明如下:
export declare class SOMETHING implements OnDestroy {
sayHello() {
// some code to say hello
}
}
但是在node_modules
(特別是角度材料)中,我在typesript
中找到了這個 function 代碼:
export declare class SOMETHING implements OnDestroy {
sayHello(parA: string, parB?: string: parC: MatSnackBarConfig): MartSnackBarRef<SimpleSnackBar>;
}
但是.... function sayHello 中的{}
在哪里?
我在哪里可以找到有關此主題的信息?
謝謝!
它被稱為方法聲明。 您正在向 typescript 聲明此方法將被實現並且它將是它的類型。
它在接口和抽象類以及方法重載中很有用。
比如重載,這里我聲明方法findOneAndUpdate
有兩種不同的調用方式,導致兩種不同的結果。
public findOneAndUpdate<U = T>(data: {
where?: unknown | {};
action?: unknown | {};
option?: MongooseOptionsReq;
session?: false | mongoose.ClientSession;
createObject: true;
mustExist?: boolean;
noLean?: boolean;
schemaPosition?: number;
}): Promise<CollectionDocument<U>>;
public findOneAndUpdate<U = T>(data: {
where?: unknown | {};
action?: unknown | {};
option?: MongooseOptionsReq;
session?: false | mongoose.ClientSession;
createObject?: false;
mustExist?: boolean;
noLean?: boolean;
schemaPosition?: number;
}): Promise<U>;
除了類型聲明,當然還需要實現方法:
public findOneAndUpdate<U = T>({
where = {},
action = {},
option = {
new: true,
},
createObject = false,
session = false,
mustExist = false,
noLean = false,
schemaPosition,
}: {
where?: unknown | {};
action?: unknown | {};
option?: MongooseOptionsReq;
session?: false | mongoose.ClientSession;
createObject?: boolean;
mustExist?: boolean;
noLean?: boolean;
schemaPosition?: number;
}): Promise<CollectionDocument<U>> | Promise<U> {
// ...
}
這與抽象方法減速密切相關 - 但沒有abstract
關鍵字更靈活。 通過這種方式,可以以更具類型意識的方式公開父 class 的形狀。
class Parent {
hello(x: number): number;
}
class Child extends Parent {
hello() {
console.log('hello');
}
}
c = new Child();
c.hello()
閱讀此處了解更多信息:
https://www.typescriptlang.org/docs/handbook/classes.html#abstract-classes
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.