繁体   English   中英

我可以使用数组变量来定义 typescript 吗?

[英]Can I use array variable to define typescript?

假设我有一个常量变量

const STATUS = {
    ACTIVE: "ACTIVE",
    DELETED: "DELETED",
  }

我有一个 function 输入是状态

const handleStatus = (status) {
//do some thing
}

我想为status定义接口,只接受'ACTIVE'和'DELETED',所以我必须像下面这样手动定义

type status = 'ACTIVE' | 'DELETED'
const handleStatus = (status : status) {
//do some thing
}

我可以做类似的事情吗

type status = Object.values(STATUS)

谢谢!

编辑:我定义type status = (typeof STATUS)[keyof typeof STATUS]但是当我尝试检查状态是否有效时

const validStatus = Object.values(STATUS)
if(!validStatus.includes(status)) {
  //do something
}

Typescript 抛出错误

Argument of type 'string' is not assignable to parameter of type ...

有 2 个选项供您选择。 作为在这种情况下使用enum进行切换的评论中的建议,另一种方法是使用keyof关键字,因为仍然希望将字符串文字作为类型:

type Status = keyof typeof STATUS;

PS:如果您更喜欢将值作为类型而不是键,则需要进行更多调整:

const STATUS = {...} as const // mark it as constant

type Status = (typeof STATUS)[keyof typeof STATUS];

对新增请求的答复

看起来像是打字与其价值之间的误解。 您不能将类型设置为值,这意味着您必须使用已定义的类型创建一个变量(不要将类型名称定义为小写status ),因此示例如下:

type Status = (typeof STATUS)[keyof typeof STATUS];

// this is the value which needs to create with your created type
const status: Status = 'ACTIVE';

// you can set this type as: `Status[]` or 
// you don't need to do so cause
// tsc can infer correct type as `Status[]`
const validStatus = Object.values(STATUS);

if(!validStatus.includes(status)) {
  // ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM