Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
Argumentos condicionales

Me gustaría crear una función que restrinja los argumentos pasados. dpr y w no deben pasarse al mismo tiempo. Aquí está mi intento:

Patio de juegos

 interface W { w: number } interface Dpr { dpr: number } type Srcset<T> = { url: string } & WidthOrDpr<T> type WidthOrDpr<T> = T extends W ? W : Dpr; function formatSrcset<T extends W | Dpr>(options: Srcset<T>) { } formatSrcset({ url: '//', dpr: 1 }); // ok formatSrcset({ url: '//', w: 1 }); // ok formatSrcset({ url: '//', w: 1, dpr: 1 }); // should fail

Me gustaría evitar sobrecargas de funciones .

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Este no es el código más conciso, pero ¿qué pasa si obligas a dpr / w a no estar definido al definir dos interfaces para las diferentes opciones de argumento? Algo como esto:

 type Args1 = { dpr: number, w?: undefined }; type Args2 = { dpr?: undefined, w: number }; type Srcset<T> = { url: string } & (Args1 | Args2);
about 4 years ago · Juan Pablo Isaza Relatório

0

Puede usar RequireAtLeastOne type-fest

 // code from sindresorhus/type-fest type RequireAtLeastOne< ObjectType, KeysType extends keyof ObjectType = keyof ObjectType, > = { // For each `Key` in `KeysType` make a mapped type: [Key in KeysType]-?: Required<Pick<ObjectType, Key>> & // 1. Make `Key`'s type required // 2. Make all other keys in `KeysType` optional Partial<Pick<ObjectType, Exclude<KeysType, Key>>>; }[KeysType] & // 3. Add the remaining keys not in `KeysType` Except<ObjectType, KeysType>;

En tu caso

 type Args = RequireAtLeastOne<{ url: string dpr?: number w?: number }, 'dpr' | 'w'> function fn({ url, dpr, w }: Args) {...}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda