typescript - 模板字符串如何排除某些字段?
问题描述
我想为方法字段写约束
type event = {
[k: `on${string}`]:(e:string)=>void
}
但我希望事件参数是不以'on'开头的字段的数字
type event = {
[k: `${xxx}`]:(e:number)=>void // XXX does not start with 'on'
}
我怎么写这个XXX?
解决方案
我已经尝试了以下...看看是否有帮助...但是,应用的技巧是将密钥拆分为来自两种不同的类型,然后使用来自 Typescript的映射类型的支持将它们组合起来。
type GuessItsACallback = (x: number) => void;
type WithoutOnKeys = {
key1: GuessItsACallback
key2: GuessItsACallback
}
type WithOnKeys = {
onKey1: GuessItsACallback,
onKey2: GuessItsACallback
}
type CombinedKeys = WithoutOnKeys & WithOnKeys;
const combinedValue: CombinedKeys = {
key1: (x: number) => console.log(x + 10),
key2: (y: number) => console.log(y + 20),
onKey1: (x: number) => console.log(x + 10),
onKey2: (x: number) => console.log(x + 10)
}
const withoutOnValues: WithoutOnKeys = combinedValue;
const withOnValues: WithOnKeys = combinedValue;
withoutOnValues.key1(30);
withOnValues.onKey1(50);
type DesiredEvents = {
[Property in keyof CombinedKeys]: GuessItsACallback
}
const eventsContainer: DesiredEvents = combinedValue;
const eventsContainerWithoutOnKeys: WithOnKeys = eventsContainer;
const eventsContainerWithOnKeys: WithoutOnKeys = eventsContainer;
推荐阅读
- reactjs - 添加 ag-grid 企业时出现 Airframe-react Ag-grid 错误
- rabbitmq - 测试 SpringCloudStream Consumer 的最小上下文
- json - jq将元素添加到对象数组中的每个对象
- mailgun - 使用 mailgun-js v0.8.1 挂断套接字
- web-applications - 具有实时数据的 Web 应用程序流程图/流程图
- jestjs - 如何在 NodeJS 和 jest 中记录深度堆栈跟踪?
- css - 将标签移动到待办事项栏的顶部
- c# - 我正在尝试在我的项目中混合使用 netstandard2.0 和 net48,以逐步过渡到 .NET Core。如何解决此管道警告?
- django - 请求总是返回从 React-Native 发送到 Django 的未经授权的
- php - 如何在php中上传pdf或doc或txt文件