I have an api response that will return either:
geoblocked: false
or
geoblocked: {
country: {
id: number;
}
}
I thought the interface for the above would be as simple as
export interface Country {
country: {
id: number;
name: string;
countryCode: string;
};
}
export interface SiteDataType {
geoblocked: Country | boolean;
}
However, with the above interface I am getting a type error when country exists. How can I expect type of boolean false?
CodePudding user response:
Problem is not with boolean one, is with the Country interface:
With these interfaces:
export interface Country {
country: {
id: number;
name: string;
countryCode: string;
};
}
export interface SiteDataType {
geoblocked: Country | boolean;
}
Those objects are ok:
let myvar: SiteDataType = {
geoblocked: false
}
myvar = {
geoblocked: {
country: {
id: 1,
name: "hi",
countryCode: "ES"
}
}
}
But this object is not valid:
myvar = {
geoblocked: {
country: {
id: 1
}
}
}
because both name and countryCode are required. So try with this interface for Country
, to make not required both name
and countryCode
just adding a ?
to the properties:
export interface Country {
country: {
id: number;
name?: string;
countryCode?: string;
};
}
and of course, if true
is not a valid type for geoblocked
you can also set it on false
or Country
:
export interface SiteDataType {
geoblocked: Country | false;
}