在 Vue.js 中输入道具时出现尾随逗号错误

Trailing comma error with prop typing in Vue.js

我在 Vue 中使用 Typescript。我想为我的道具添加打字,但 lint 给我一个尾随逗号的错误。在这种情况下:

  21:6  error  Parsing error: Unexpected token, expected ","

   9 |       type: Object,
  10 |       required: true
> 11 |     } as PropOptions<MenuItem[]>,
     |       ^
  12 |   },
  13 |   data: () => ({}),
  14 | })

代码:

<script lang="ts">
import Vue, { PropOptions } from 'vue'
import { MenuItem } from '~/types/data'

export default Vue.extend({
  name: 'UiSubmenu',
  props: {
    submenuProp: {
      type: Object,
      required: true,
    } as PropOptions<MenuItem[]>,
  },
  data: () => ({}),
})
</script>

我尝试禁用逗号悬挂规则但没有结果。

我认为问题不在于结尾的逗号。如果删除它,ts 仍然会抱怨类型断言。

也许你可以尝试这样的事情:

const myProp: MyCustomType = {
  default: "hello",
  type: String
};

export default {
  name: "App",
  props: {
    myProp,
  },
  // ...
};

问题出在你的打字稿语法上。 您必须使用 returns 正确类型的函数来输入道具。

像那样:

<script lang="ts">
import Vue, { PropOptions } from 'vue'
import { MenuItem } from '~/types/data'

export default Vue.extend({
  name: 'UiSubmenu',
  props: {
    submenuProp: {
      type: Object as () => PropOptions<MenuItem[]>,
      required: true,
    },
  },
  data: () => ({}),
})
</script>

这是我的 tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ],
      "@tests/*": [
        "tests/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

这是我的 tslint.json

{
  "defaultSeverity": "warning",
  "extends": [
    "tslint:recommended"
  ],
  "linterOptions": {
    "exclude": [
      "node_modules/**"
    ]
  },
  "rules": {
    "quotemark": [true, "single"],
    "indent": [true, "spaces", 2],
    "semicolon": [true, "never"],
    "eofline": true,
    "interface-name": false,
    "ordered-imports": false,
    "object-literal-sort-keys": false,
    "newline-before-return": true,
    "no-consecutive-blank-lines": true,
    "arrow-parens": [true, "ban-single-arg-parens"],
    "no-bitwise": false,
    "variable-name": {
      "options": [
        "ban-keywords",
        "check-format",
        "allow-leading-underscore",
        "allow-pascal-case"
      ]
    }
  }
}