Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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 answers
Answer question

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 Report

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 Report

0

Did so

type TBody<T> = {
       success: boolean;
       user?: T;
    }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!