javascript - 打字稿中的条件类型可以依赖于自身的值吗?
问题描述
我可以在打字稿中实现这种类型吗?
type Someone = {
who: string;
}
type Someone = Someone.who === "me" ? Someone & Me : Someone;
解决方案
下面是一个最低限度的工作示例:
type Someone<T extends string> = {
who: T;
}
type Me = {
me: boolean;
}
type Thisone<T extends string> = T extends 'me' ? Someone<T> & Me : Someone<T>;
function whoami<T extends string>(who: T) {
return {
who,
me: who === 'me' ? true : undefined
} as Thisone<T>
}
const a = whoami('you');
const b = whoami('me');
a.who; // ok
a.me; // error
b.who; // ok
b.me; // ok
推荐阅读
- strapi - 如何显示使用编辑器放置的图像
- applescript-objc - 如何使用 NSAlert 获取单击按钮的返回值
- oracle - Oracle 12g Weblogic 服务器 MEDREC WADL
- javascript - 当达到字符限制而不破坏单词时,如何在字符串中添加换行符?
- arm - 在具有 FreeRTOS 的微控制器上未静态分配的 RAM 会发生什么情况
- python - selenium.common.exceptions.ElementNotInteractableException:无法通过键盘访问
- python - 如何让python等待“无”,首先运行事件循环
- android - 如何使用扩展 BaseActivity 的数据绑定显示 childActivity?
- jquery - 如何通过 jquery 更改具有页面高度的按钮的位置?
- react-native - 通过主题设置导航栏的背景颜色以响应本机应用程序