接口键作为值而不是类型

huangapple go评论84阅读模式
英文:

Interface key as value instead of type

问题

  1. export interface 动作 {
  2. 启动: "start",
  3. 停止: "stop"
  4. }
  5. // 从库中导入动作后,需要进行如下的相等性检查:
  6. import { 动作 } from '我的库';
  7. // 在某个逻辑中,x 是字符串类型,但本质上是动作中的一种
  8. if (x === 动作.启动) { }
英文:

A third-party library exposes different actions as part of an interface as given below:

  1. export interface actions {
  2. start: "start",
  3. stop: "stop"
  4. }

After importing actions from this library, there's an equality check to be done as given below:

  1. import { actions } from 'my-library';
  2. // as part of some logic where x is of string type but is essentially one of the actions
  3. if (x === actions.start) { }

The above code throws the following error:

  1. 'actions' only refers to a type, but is being used as a value here.

How can we use actions interface like an enum?

答案1

得分: 1

以下是翻译好的部分:

"你不能在运行时使用一个类型,不管它来自哪里。所以如果这是来自一个你无法控制的依赖项,那么你无法做太多事情。

如果库没有导出要使用的值,那么你不应该将其用作值。

你可能应该做类似这样的事情:

  1. export interface actions {
  2. start: "start",
  3. stop: "stop"
  4. }
  5. const x: keyof actions = 'start'
  6. if (x === 'start') console.log('start')

这里你确实获得了枚举的行为,因为TypeScript会在你使用不是 action 的东西时发出警告。

  1. if (x === 'bad') console.log('bad')
  2. // 这个比较似乎是不打算的,因为类型 ' "start" ' 和 ' "bad" ' 没有重叠。(2367)

不了解该库的具体情况,很难提供更好的建议。"

英文:

You cannot use a type at runtime, no matter where it comes from. So if this is coming from a dependency you don't control, then there isn't much you can do.

If the library does not export a value to use, then you aren't meant to use it as a value.

You are probably meant to do something like:

  1. export interface actions {
  2. start: "start",
  3. stop: "stop"
  4. }
  5. const x: keyof actions = 'start'
  6. if (x === 'start') console.log('start')

And you do get enum like behavior here because typescript will complain if you use something that isn't an action.

  1. if (x === 'bad') console.log('bad')
  2. // This comparison appears to be unintentional because the types '"start"' and '"bad"'
  3. // have no overlap.(2367)

Without knowing the specifics of that library, it's hard to give better advice.

huangapple
  • 本文由 发表于 2023年2月16日 02:23:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75463979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定