【问题标题】:Check if string array is all unions检查字符串数组是否都是联合
【发布时间】:2020-05-24 17:40:25
【问题描述】:

我有以下几点:

import * as core from '@actions/core'
import { GitHub } from '@actions/github'
import { context } from '@actions/github'

const valid_statuses = ["queued", "in_progress", "completed"] as const;
type Status = typeof valid_statuses[number]

function IsValidJson(str: string): boolean {
    try {
        JSON.parse(str)
    } catch (e) {
        return false
    }
    return true
}

function StringArrayFromJson(json: string): [string] {
    if (json != null && typeof json === 'string' && !IsValidJson(json)) {
        json = `[${ json }]`
    }

    if (json == null) {
        json = '[]'
    }

    if (!IsValidJson(json)) {
        throw new Error(`Invalid JSON: ${ json }`)
    }
    return JSON.parse(json) as [string]
}

async function main(): Promise<void> {
    try {
        let statuses = StringArrayFromJson(core.getInput('statuses', { required: true }))

        //item in valid_statuses returns false!
        if (statuses.length <= 0 || !statuses.every(item => { return item in valid_statuses })) {
            core.setFailed(`ERROR: statuses must be an array of valid status strings. Got: ${ JSON.stringify(statuses) }`)
            return
        }

        console.log('Success')
    } catch (error) {
        core.setFailed(error.message)
    }
}

main()

我意识到代码转换为以下 Javascript:

const valid_statuses = ["queued", "in_progress", "completed"]
console.log("in_progress" in valid_statuses); //Returns false

为什么我不能检查我的字符串是否是一个有效的联合?

编辑(TSConfig):

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "esnext",
        "lib": [
            "es2015",
            "es2017"
        ],
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitAny": true,
        "removeComments": false,
        "preserveConstEnums": true
    },
    "include": [
        ".github/actions/**/*.ts",
        "**/*.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}

编辑(package.json):

{
  "private": true,
  "name": "create-check-action",
  "scripts": {
    "build": "tsc",
    "test": "tsc --noEmit && jest"
  },
  "license": "ISC",
  "dependencies": {
    "@actions/core": "^1.2.4",
    "@actions/github": "^2.2.0"
  },
  "devDependencies": {
    "@types/jest": "^25.2.3",
    "@types/node": "^14.0.5",
    "jest": "^26.0.1",
    "ts-jest": "^26.0.0",
    "typescript": "^3.9.3"
  }
}

【问题讨论】:

  • 请添加您的 tsconfig。我的猜测是您需要使用更新的 javascript 版本
  • @zirmax;已添加tsconfig。
  • 我无法使用您提供的代码和配置重现您的错误。还有更多代码吗?请同时添加您的 package.json
  • 我现在已经包含了所有代码和整个package.json。这是一个很大的github action,所以我最初不想让帖子太大,所以我把它剪到了错误所在的位置。但是,我现在已经包含了运行它所需的一切。我执行npm run build,然后将其推送到 github 存储库并让操作执行。
  • 使用in 不起作用,因为它检查的是键,而不是值("a" in {a: 1} 是true,但"a" in ["a"] 是false)。 includes 和 indexOf 的问题是 TypeScript 打字问题,答案在链接的重复问题中。处理这个问题的最简单方法是(valid_statuses as readonly string[]).indexOf(item) 或(valid_statuses as readonly string[]).includes(item)。如果需要,您可以使用find(),但这是一种解决方法,似乎并没有解决上述问题。您仍然需要答案还是要删除问题?

标签: typescript


【解决方案1】:

已经尝试过includes?

const valid_statuses = ["queued", "in_progress", "completed"]

console.log(valid_statuses.includes("in_progress"));
console.log(valid_statuses.includes("queued"));
console.log(valid_statuses.includes("something_else"));

【讨论】:

  • 我在 OP 中添加了一张图片,显示了我在尝试 includes 时遇到的错误。
  • 我不知道你为什么在const valid_statuses = ["queued", "in_progress", "completed"] as const; 的末尾添加as const 如果删除它会发生什么?
  • stackoverflow.com/questions/36836011/… 这就是我从那里得到的。如果我最后不加const,会报编译器错误string在做str as Status时不能转换成type Status。
猜你喜欢
  • 2020-07-06
  • 2017-10-30
  • 2015-01-08
  • 2017-03-17
  • 1970-01-01
  • 2021-12-14
  • 2014-04-09
  • 2022-06-30
  • 2014-09-24
相关资源
最近更新 更多