首页 > 解决方案 > 结构类型与联合失败?

问题描述

我不太明白为什么以下内容无法编译

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

解决方案


你用的是什么版本的打字稿?Typescript 3.5 引入了更智能的联合类型检查,应该可以解决您的问题。我认为打字稿游乐场尚未使用该版本。


推荐阅读