typescript - ¿Cómo pasar parámetros opcionales mientras se omiten otros parámetros opcionales?
Dada la siguiente firma:
export interface INotificationService {
error(message: string, title?: string, autoHideAfter?: number);
}
¿Cómo puedo llamar a la función error() sin especificar el parámetro title, pero configurando autoHideAfter a, digamos, 1000?
Respuesta #1
Como se especifica en la documentación, use undefined:
export interface INotificationService {
error(message: string, title?: string, autoHideAfter? : number);
}
class X {
error(message: string, title?: string, autoHideAfter?: number) {
console.log(message, title, autoHideAfter);
}
}
new X().error("hi there", undefined, 1000);
Enlace del parque infantil.
Respuesta #2
Desafortunadamente, no hay nada como esto en TypeScript (más detalles aquí: https://github.com/Microsoft/TypeScript/issues/467)
Pero para evitar esto, puedes cambiar tus parámetros para que sean una interfaz:
export interface IErrorParams {
message: string;
title?: string;
autoHideAfter?: number;
}
export interface INotificationService {
error(params: IErrorParams);
}
//then to call it:
error({message: 'msg', autoHideAfter: 42});
Respuesta #3
Otro enfoque es:
error(message: string, options?: {title?: string, autoHideAfter?: number});
Entonces, cuando quieras omitir el parámetro de título, simplemente envía los datos así:
error('the message', { autoHideAfter: 1 })
Preferiría esta opción porque me permite agregar más parámetros sin tener que enviar los otros.
También puedes usar el tipo Partial<T> en la firma del método, pero en este caso tienes que crear una interfaz para tus opciones:
interface IMyOptions {
title: string;
autoHideAfter: number;
}
Y entonces la firma del método puede verse así:
error(message: string, options?: Partial<IMyOptions>);
El uso es el mismo que el de arriba.
El tipo Partial<T> ya debería estar declarado en los tipos globales de la siguiente manera:
type Partial<T> = {
[P in keyof T]?: T[P];
};
Respuesta #4
puedes usar una variable opcional con ? o si tienes múltiples variables opcionales con ..., ejemplo:
function details(name: string, country="CA", address?: string, ...hobbies: string) {
// ...
}
En lo anterior:
namees obligatoriocountryes obligatorio y tiene un valor predeterminadoaddresses opcionalhobbieses un arreglo de parámetros opcionales
Respuesta #5
Esto es casi lo mismo que la respuesta de @Brocco, pero con un giro ligero: pasa los parámetros opcionales solo en un objeto. (Y también haz que el objeto de parámetros sea opcional).
Termina siendo algo así como los **kwargs de Python, pero no exactamente.
export interface IErrorParams {
title?: string;
autoHideAfter?: number;
}
export interface INotificationService {
// make params optional so you don't have to pass in an empty object
// in the case that you don't want any extra params
error(message: string, params?: IErrorParams);
}
// all of these will work as expected
error('A message with some params but not others:', {autoHideAfter: 42});
error('Another message with some params but not others:', {title: 'StackOverflow'});
error('A message with all params:', {title: 'StackOverflow', autoHideAfter: 42});
error('A message with all params, in a different order:', {autoHideAfter: 42, title: 'StackOverflow'});
error('A message with no params at all:');
