Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 11571

How to create an interface with generic, conditional and optional property?

$
0
0

I am trying to create an interface which involves conditional types but I have an issue related to optional parameter.I receiveType 'false' is not assignable to type 'true' error for my boolean property.

react-select library is inspired me to build this behaviour. They have used it to handle isMulti property to decide value is either MultiValue or SingleValue

export declare type OnChangeValue<Option, IsMulti extends boolean> = IsMulti extends true ? MultiValue<Option> : SingleValue<Option>;

reference link: https://github.com/JedWatson/react-select/blob/master/packages/react-select/src/Select.tsx

Below code playground link

interface Prop1 {  iconPosition: string;}interface Prop2 {}export interface IDateRangeFilter<  V extends object,  WithCustomInputT extends boolean = true> {  to: Partial<WithCustomInputT extends false ? Prop2 : Prop1>;  fromName: keyof V;  withCustomInput: WithCustomInputT;}export interface IFilterOptions<KeyType extends keyof any, V extends object> {  field?: KeyType;  date?: IDateRangeFilter<V>;}export type IFilterOptionsSingleType<T extends object> = IFilterOptions<  keyof T,  T>;interface Ifilter {  ActivityStartDate: string;}// final declarationexport const ReferralsFilters: IFilterOptionsSingleType<Ifilter>[] = [  {    date: {      to: {        iconPosition: "end",      },      fromName: "ActivityStartDate",      withCustomInput: false, // Error: Type 'false' is not assignable to type 'true'    },  },];

The aim here is that

  • if withCustomInput key is true, Prop1 interface will be the type for to key.
  • if withCustomInput key is false, Prop2 interface will be the type for to key.

Viewing all articles
Browse latest Browse all 11571

Trending Articles