typescript - 结构类型与联合失败?
问题描述
我不太明白为什么以下内容无法编译:
interface IPreciousMetal {
type: "Silver" | "Gold"
}
interface ICryptoCurrency {
type: "Bitcoin" | "Litecoin"
}
type Asset = ICryptoCurrency | IPreciousMetal;
function process(assetType: Asset["type"]) {
const asset = { type: assetType };
processImpl(asset); // Error
}
function processImpl(asset: Asset) {
console.log(asset.type);
}
为参数传递的参数assetType
必须输入类型,使其与Asset
类型兼容。但是,当使用所述参数值创建对象时,编译器会抱怨。
解决方案
你用的是什么版本的打字稿?Typescript 3.5 引入了更智能的联合类型检查,应该可以解决您的问题。我认为打字稿游乐场尚未使用该版本。
推荐阅读
- javascript - 如何在 Javascript 中调用背景图像 URL
- dart - 在 dart 中的函数内声明一个类
- ios - 我不断收到致命错误:在展开可选值时意外发现 nil
- c# - 是否可以从存储过程访问 Azure Blob?
- javascript - p5 Uncaught (in promise) 在另一个类中实例化对象时出错
- c - valgrind asan 运行时不在初始库列表中
- python - 如何遍历不同的标签名称(h3)并使用 selenium 和 python 比较它们的文本?
- reactjs - 托管具有实时更新支持的 ReactApp 的最佳方式
- javascript - 将元素移动到其父元素的底部时出现问题
- mysql - 如何在 WHERE 子句中使用 GREATER THAN / LESS THEN 作为动态参数?