首页 > 解决方案 > 模板字符串如何排除某些字段?

问题描述

我想为方法字段写约束

  type event = {
   [k: `on${string}`]:(e:string)=>void
  }

但我希望事件参数是不以'on'开头的字段的数字

  type event = {
   [k: `${xxx}`]:(e:number)=>void //  XXX does not start with 'on'
  }

我怎么写这个XXX?

标签: typescript

解决方案


我已经尝试了以下...看看是否有帮助...但是,应用的技巧是将密钥拆分为来自两种不同的类型,然后使用来自 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;

推荐阅读