0

Imagine I have a type called Person, which for person with or without a job. If person with a job, need to provider a job details which is varying by passing Job generic.

Ideally, I thought this should work: type Person<Job = undefined> = { name: string, job: Job extends undefined? never : Job }, but not.

I have to code like: type People<Job = undefined> = Job extends undefined ? { name: string } : { name: string, job: Job } to work, which is verbose.

Anyone can give a better solution? Thanks. Please check this playground or read below:

type Teacher = { school: string }
type Engineer = { company: string }
type Job = Teacher | Engineer

// type People<Job = undefined> = Job extends undefined ? { name: string } : { name: string, job: Job }   // passed, but a lot verbose
type Person<Job = undefined> = { name: string, job: Job extends undefined? never : Job  }                 // error: personWithoutJob missing job 


const personWithoutJob: Person = { name: 'Ron' } 
const personWithJob: Person<Teacher> = { name: 'Angela', job: { school: 'a' } }
3
  • 1
    It's quite awkward to use generics for that. I'd expect PesonWithJob extends Person and PersonWithoutJob extends Person as two different interfaces. Commented Apr 1, 2020 at 22:55
  • type Person<Job> = { name?: string, job?: Job } ? Commented Apr 1, 2020 at 22:56
  • @JohnPeters that allows for personWithJob: Person<Teacher> = { name: "Angela" } which shouldn't be valid. Commented Apr 1, 2020 at 22:59

1 Answer 1

1

A good approach is an intersection type.

Like this:

type Person<Job = undefined> = { name: string } & (Job extends undefined ? {} : { job: Job });

updated playground

official intersection types documentation

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it is great. The & is great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.