【问题标题】:Exclude from string results string [duplicate]从字符串结果字符串中排除 [重复]
【发布时间】:2021-10-27 13:33:45
【问题描述】:

我想定义一个类型,其中所有属性都是只读的,看起来像 key:string value:string,但 'set' 属性是一个函数。

我尝试了以下方法:

type Attributes = {
  readonly [key in Exclude<string, 'set'>]:string
} & { 
  readonly set: (attr:string, value:string) => void 
}

我的问题是Exclude&lt;string, 'set'&gt; 被“简化”回string。有更多经验的人可以解释为什么 TypeScript 会这样做吗?一些建议如何实现我只知道几个属性键(但可以有更多)的类型可以帮助我。

感谢您的宝贵时间和回答!

【问题讨论】:

  • microsoft/TypeScript#29317 中对否定类型进行了试验,但从未将其纳入语言。所以没有办法说string &amp; not 'set'Exclude 实用程序类型不会这样做,因为它只会从联合中删除东西,而 string 不是联合。由于您的主要问题似乎实际上是关于拥有“默认”或“休息”属性,因此我已将其作为重复项关闭,this answer 解释了这些选项。如果我在这里翻译该代码,我会得到this

标签: typescript


【解决方案1】:

目前在 typescript 中,无法创建像“除 ... 之外的任何字符串”这样的类型,Exclude&lt;string, '...'&gt; 总是导致string。这只是我们现在必须处理的 typescript 的一个限制。

无论如何,这种类型似乎有效

type Attributes = {
  readonly [key: string]: string
} & { 
  readonly set: (attr:string, value:string) => void 
}

你不能分配一个没有set属性的对象,并且这个属性必须是你在那里指定的一个函数,所以看起来你可以使用它

【讨论】:

  • 当我调用set函数时,TS编译器报错:This expression is not callable. Not all constituents of type 'string | ((attr: string, value: string =&gt; void)' are callable. Type 'string' has no call signatures.
  • 哦,是的,忘记了。然后我相信在打字稿中不可能做到这一点,你必须在调用你的函数时添加类型断言
猜你喜欢
  • 2020-05-31
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
  • 2018-03-28
  • 2020-03-30
相关资源
最近更新 更多