想象一下,我有一个名为Person
的类型,该类型适用于有工作或无工作的人。如果有工作,则需要提供工作详细信息,该详细信息会通过传递Job
泛型而有所不同。
理想情况下,我认为这应该可行:type Person<Job = undefined> = { name: string, job: Job extends undefined? never : Job }
,但不行。
我必须像这样进行编码:type People<Job = undefined> = Job extends undefined ? { name: string } : { name: string, job: Job }
,这很冗长。
任何人都可以提供更好的解决方案吗?谢谢。请检查this playground或阅读以下内容:
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' } }
答案 0 :(得分:1)
一种好的方法是交叉点类型。
赞:
type Person<Job = undefined> = { name: string } & (Job extends undefined ? {} : { job: Job });