Tipos función y sobrecargas en TypeScript
Una firma de llamada como tipo, parámetros opcionales y por defecto, sobrecargas.
type Formatter = (value: number, digits?: number) => string;
const fixed: Formatter = (value, digits = 1) => value.toFixed(digits);
function first(values: string[]): string | undefined;
function first(values: string[], fallback: string): string;
function first(values: string[], fallback?: string): string | undefined {
return values[0] ?? fallback;
}
type Handler = {
(event: string): void;
readonly type: "handler";
};
const handler = ((event: string) => console.log(event)) as Handler;
console.log(fixed(2.345, 2), first([], "none"), first(["a"]));
console.log(typeof handler);
Cómo funciona
- Un tipo función puede escribirse en línea o con nombre.
- Las firmas de sobrecarga estrechan el tipo de retorno según la forma del argumento.
- La firma de implementación no puede llamarse desde afuera.
Palabras clave y builtins usados aquí
Formatterasconstfunctionnumberreadonlyreturnstringtype
El intento, en números
- Líneas
- 19
- Caracteres a escribir
- 585
- Tokens
- 166
- Ritmo de tres estrellas
- 95 tpm
Al ritmo de tres estrellas de 95 tokens por minuto, este intento toma unos 105 segundos.
Paso 2 de 5 en Funciones y tuplas; paso 17 de 23 en Tipos y anotaciones.