简体   繁体   中英

TypeScript: How do I narrow / write a guard for a complex conditional type?

Given the following MultiselectValue conditional type, how do I make it resolve to either LabeledValue<T> or Array<LabeledValue<T>> based on the value of multiple or via a guard inside Comp ?

export interface LabeledValue<T = unknown> {
  label: string;
  value: T;
}

export type MultiselectValue<T, Multiple> = Multiple extends (undefined | false)
  ? LabeledValue<T>
  : Array<LabeledValue<T>>;

export type MultiselectProps<T, Multiple extends boolean | undefined> = {
  multiple: Multiple;
  value: MultiselectValue<T, Multiple>;
}

Comp({
  multiple: true,
  value: [{ // tsc complains if not an array (as expected) because 'multiple' is 'true'
    label: 'Option 1',
    value: 5
  }]
});

function Comp<T, Multiple extends boolean | undefined = undefined>(props: MultiselectProps<T, Multiple>) {
  const { multiple, value } = props;

  if (multiple) {
    // value is an arrray here
  } else {
    // value is a string here
  }
}

TS Playground link

The easiest way is to actually change the definition of MultiselectProps :

type MultiselectProps<T, Multiple extends boolean | undefined> = Multiple extends (undefined | false) ? {
  multiple: Multiple;
  value: LabeledValue<T>;
} : {
  multiple: Multiple;
  value: Array<LabeledValue<T>>;
};

Now, in the function body, props is a discriminated union (unresolved type), which means you can narrow it like you already have done.

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM