There are TONS of questions about conditional types based on a value. However I'm not sure can scenario below be implemented at all.
I'm getting acquainted with conditional types and I'm wondering if it's possible to make a conditional type that will be dependant on a non-empty string.
Let's consider next interface:
interface Animal {
dogName: string;
canBark: boolean;
}
and
interface AnimalToBeMapped {
dogsNickname?: string;
/// some other props
}
I'm using this interface to map an object
function mapAnimal(animal: AnimalToBeMapped): Animal {
return {
dogName: animal.dogsNickname,
canBark: !animal.dogsNickname
}
}
I'm setting canBark property to true only when the argument object has a dogName property set (should work also for empty string vs. non-empty string).
What I want to do is to add additional type-safety to my Animal interface (if someone is setting dogName manually to be defined then I want to force canBark property to be true and vise versa).
example:
const exmpl1: Animal = {
dogName: 'Rex',
canBark: false // I want an error here
}
and
const exmpl2: Animal = {
dogName: '',
canBark: true // An error here
}
dogNamemanually to be defined then I want to forcecanBarkproperty to be true and vise versa", I think about scenarios like handling user input or API fetch results. You're out of luck there. You need to write validation logic for that.