Reputation: 6725
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' } }
Upvotes: 0
Views: 343
Reputation: 157
A good approach is an intersection type.
Like this:
type Person<Job = undefined> = { name: string } & (Job extends undefined ? {} : { job: Job });
official intersection types documentation
Upvotes: 1