Typescript: Expect Object or Boolean(false)



我有一个api响应,它将返回其中一个:

geoblocked: false

geoblocked: {
country: {
id: number;
}
}

我以为上面的界面会像一样简单

export interface Country {
country: {
id: number;
name: string;
countryCode: string;
};
}
export interface SiteDataType {
geoblocked: Country | boolean;
}

然而,使用上面的界面,当国家存在时,我会得到一个类型错误。我怎么能期望布尔类型为false?

问题不在于布尔值,而在于Country接口:

使用这些接口:

export interface Country {
country: {
id: number;
name: string;
countryCode: string;
};
}
export interface SiteDataType {
geoblocked: Country | boolean;
}

这些对象还可以:

let myvar: SiteDataType = {
geoblocked: false
}
myvar = {
geoblocked: {
country: {
id: 1,
name: "hi",
countryCode: "ES"
}
}
}

但此对象无效:

myvar = {
geoblocked: {
country: {
id: 1
}
}
}

因为name和countryCode都是必需的。因此,尝试使用Country的这个接口,使不需要namecountryCode,只需向属性中添加一个?

export interface Country {
country: {
id: number;
name?: string;
countryCode?: string;
};
}

当然,如果true不是geoblocked的有效类型,您也可以将其设置为falseCountry:

export interface SiteDataType {
geoblocked: Country | false;
}

最新更新