考虑到下面的类型、接口和 getData 函数,我试图找到一种利用可区分联合的方法,以便 TS 编译器可以将返回类型缩小getData(source: DOSources)为关联的DOTypes
// Expected behavior
const result = getData("dataObjectA");
// result.data should be a string but in this case the TS compiler will complain
// that data does not have the toLowerCase() function
result.data.toLowerCase();
Run Code Online (Sandbox Code Playgroud)
示例代码
interface DataObjectA {
source: "dataObjectA";
data: string;
}
interface DataObjectB {
source: "dataObjectB";
data: number;
}
type DOTypes = DataObjectA | DataObjectB
type DOSources = DOTypes["source"];
async function getData(source: DOSources) {
const response = await fetch(`https://some-random-endpoint/`, {
method: …Run Code Online (Sandbox Code Playgroud)