Ron
Ron

Reputation: 6725

Typescript: How to indicate a property nullable by using generic

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

Answers (1)

Francisco
Francisco

Reputation: 157

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

Upvotes: 1

Related Questions