接口键作为值而不是类型

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

Interface key as value instead of type

问题

export interface 动作 {
   启动: "start",
   停止: "stop"
}

// 从库中导入动作后,需要进行如下的相等性检查:
import { 动作 } from '我的库';

// 在某个逻辑中,x 是字符串类型,但本质上是动作中的一种
if (x === 动作.启动) { }
英文:

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

export interface actions {
   start: "start",
   stop: "stop"
}

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

import { actions } from 'my-library';

// as part of some logic where x is of string type but is essentially one of the actions
if (x === actions.start) { }

The above code throws the following error:

'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

以下是翻译好的部分:

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

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

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

export interface actions {
   start: "start",
   stop: "stop"
}

const x: keyof actions = 'start'
if (x === 'start') console.log('start')

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

if (x === 'bad') console.log('bad')
// 这个比较似乎是不打算的,因为类型 ' "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:

export interface actions {
   start: "start",
   stop: "stop"
}

const x: keyof actions = 'start'
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.

if (x === 'bad') console.log('bad')
// This comparison appears to be unintentional because the types '"start"' and '"bad"'
//   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:

确定