本文的翻译于<<Effective TypeScript>>, 特别感谢!! ps: 本文会用简洁, 易懂的语言描述原书的所有要点. 如果能看懂这文章,将节省许多阅读时间. 如果看不懂,务必给我留言, 我回去修改.
技巧47:将出现在公共api的类型导出
越使用ts,你就越期待直接使用第三方库定义的type,interface,而不是自己定义。但是第三方库却不导出相应的。幸运的是,ts有丰富的工具找到需要的type,interface:
假如你想创造的一些secret,未导出的types:
interface SecretName {
first: string;
last: string;
}
interface SecretSanta {
name: SecretName;
gift: string;
}
export function getGift(name: SecretName, gift: string): SecretSanta {
// ...
}
使用者无法得到 SecretName 或者 SecretSanta, 只能得到 getGift。没关系,我们可以通过这样的方法得到:
type MySanta = ReturnType<typeof getGift>; // SecretSanta
type MyName = Parameters<typeof getGift>[0]; // SecretName
如果说你作为type的作者,你应该帮你的读者做明确的导出