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

158
Visualizações
How to pass any type using generics?

Good day

Trying to deal with generics

There are 2 types

  1. TUserInfo
type TUserInfo = {
   id: num,
   readonly fname: string,
   readonly lname: string
}
  1. TBody
type TBody = {
   success: boolean,
   user?: any
}

Tell me how to pass any type to TBody (for example, TUserInfo). And user should have the same type instead of any. Thank you in advance

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

0

I think it is better to use discriminated unions in this case:


export interface User {
    id: number,
    fname: string,
    lname: string
}

type Response<T> =
    | {
        success: true;
        user: T
    }
    | {
        success: false
    }

type Result = Response<User>

declare var result: Result

if (result.success) {
    result.user
} else {
    result.success // false
    result.user // error
}

I'd willing to bet that if success if false - user property should be ubdefined.

Result type is pretty popular monad. See Rust Result, F# Result

about 4 years ago · Juan Pablo Isaza Relatório

0

In typescript, you can create interfaces.

export interface TUserInfo {
    id: number,
    fname: string,
    lname: string
}

export interface TBody {
    success: boolean,
    user?: TUserInfo
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Did so

type TBody<T> = {
       success: boolean;
       user?: T;
    }
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