Termed as a method declaration, this syntax informs Typescript that the specified method will be implemented and defines its type.
Method declarations are particularly useful in Interfaces and Abstract classes, as well as for method overloading.
For example, in the following code snippet, I introduce an overload for the method findOneAndUpdate
, offering two distinct ways to invoke it, resulting in different outcomes:
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>;
In addition to declaring the types, the actual method implementation is needed:
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> {
// Method implementation goes here...
}