打字稿:如何使用泛型指示可为空的属性

时间:2020-04-01 22:49:01

标签: typescript

想象一下,我有一个名为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' } }

1 个答案:

答案 0 :(得分:1)

一种好的方法是交叉点类型。

赞:

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

updated playground

official intersection types documentation