首页 > 解决方案 > 我可以在没有 const 或强制转换的情况下使用 Typescript 字符串文字吗?

问题描述

Typescript 具有描述类型的有效字符串值的字符串文字(请参阅文档)。我的问题是,当使用过去似乎做的普通 JavaScript 对象时,我无法让它工作。

例如,我想输入购物篮中产品的有效货币。

interface Product {
  title: string;
  description: string;
  price: number;
  quantity: number;
  currency: '$' | '£';
}

如果我使用纯 JavaScript 对象,假设来自 JSON 源或 JS 文件,例如:

{
  title: 'Y Lift Neck Serum',
  description: 'This serum contains...',
  price: 400,
  currency: '$',
  quantity: 1
}

我得到错误 - Types of property 'currency' are incompatible. Type 'string' is not assignable to type '"$" | "£"'.ts(2322) "typescript": "~3.7.2"。这是因为字符串文字是字符串的子集,而不是字符串。

我发现的解决方案是强制转换使用 const但我想知道是否有一个类型定义currency可以“正常工作”。我宁愿不必添加const或添加as多行,尤其是当源文件可能是纯 JavaScript 或服务器响应时。

我也不明白在另一个项目中这是如何工作的:

// "typescript": "^3.5.3" 
export type Route = {
    path: string;
    method: '*' | 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
    vhost?: string;
    handler: (request, reply) => any;
    options: object;
    rules: object;
};

更新:我创建了一个代码演示https://codesandbox.io/s/summer-rgb-5ruv7并且错误没有出现在那里。但我仍然可以在 VS 代码中看到它——可能是本地配置问题?

类型“字符串”不可分配给类型“ 样品产品 产品类别

打字稿配置

{ // tsconfig.base.json
  "compilerOptions": {
    "target": "es5",
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": false,
    "noImplicitReturns": true,
    "jsx": "preserve"
  },
  "exclude": ["node_modules", "build", "!node_modules/@types"]
}


{ // tsconfig.json
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowSyntheticDefaultImports": true,
    "isolatedModules": true,
    "jsx": "react"
  },
  "include": ["src"]
}

标签: javascripttypescripttypes

解决方案


推荐阅读