[英]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.