2021年3月26日星期五

Conditional type based on a non-empty string

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  }  
https://stackoverflow.com/questions/66828502/conditional-type-based-on-a-non-empty-string March 27, 2021 at 02:08PM

没有评论:

发表评论