javascript - 我可以在没有 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"]
}
解决方案
推荐阅读
- java - 在缓冲图像上填充颜色时出错
- javascript - 如何在不安装运行时导入其他js文件
- python - 摆脱 Pandas Dataframe 中列中的重复字符串
- python-3.x - 如何创建元组的循环引用?
- javascript - 检查元素是否与 JavaScript 中的条件对应
- javascript - 使用纯 Javascript 或 JQuery 的 Google OAuth 2 访问令牌
- c++ - 如何在同一条线上接受两个有理输入?
- java - Spring Boot 应用程序登录成功后重定向到 http URL
- matlab - 如何根据 Simulink 中的条件获得不同的可能输入?
- r - 当闪亮的动作按钮点击(和未点击)改变颜色并记录点击值