如何将自定义类型转换为原始类型?

时间:2018-12-17 10:24:17

标签: javascript typescript types casting

我有类型

type Rating = 0 | 1 | 2 | 3 | 4 | 5 | number

现在我想做这样的事情。

let myRating:Rating = 4
let rate:number = myRating as number

如何将我的myRating转换为number基本类型?

它给我的错误是:

  

将“评级”类型转换为“数字”可能是一个错误,因为这两个类型都没有足够的重叠。如果这是故意的,请先将表达式转换为“未知”。ts(2352)

我经历过this,但是我想要的是相反的情况

编辑:

  

tsconfig.json

{
  "compilerOptions": {
    "noImplicitAny": false,
    "target": "es6",
    "allowJs": true,
    "skipLibCheck": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "strict": true
  },
  "include": [
    "src"
  ]
}

tsc版本:3.2.1

2 个答案:

答案 0 :(得分:3)

尝试:

myRating as unknown as number

另外,从您的声明中删除| number

答案 1 :(得分:0)

我认为它在打字稿更新TS 3.5.1中已修复

type Rating = 0 | 1 | 2 | 3 | 4 | 5;
let myRating:Rating = 4

现在

let rate:number = myRating;

let rate:number = myRating as number;

都可以。

TS Playground