Skip to content

Instantly share code, notes, and snippets.

@styfle
Created November 17, 2017 15:04
Show Gist options
  • Select an option

  • Save styfle/58973dbe558cd7052242bdf2b4cc4b17 to your computer and use it in GitHub Desktop.

Select an option

Save styfle/58973dbe558cd7052242bdf2b4cc4b17 to your computer and use it in GitHub Desktop.
TypeScript SO question 41705559
type Opt = { id: string, name: string }
interface MultiProps {
isMultiple: true;
options: Opt[];
id: string[];
onChange: (id: string[]) => void;
}
interface SingleProps {
isMultiple: false;
options: Opt[];
id: string;
onChange: (id: string) => void;
}
type SelectProps = MultiProps | SingleProps;
function Select(props: SelectProps) {
if (props.isMultiple) {
// works
const { id, onChange } = props;
onChange(id);
} else {
// fail
const { id, onChange } = props;
onChange(id); // error here
}
}
let m: MultiProps = {
isMultiple: true,
options: [{ id: 'a', name: 'A' }],
id: ['a'],
onChange: null
};
let s: SingleProps = {
isMultiple: false,
options: [{ id: 'a', name: 'A' }],
id: 'a',
onChange: null
};
Select(m);
Select(s);
@styfle

styfle commented Nov 17, 2017

Copy link
Copy Markdown
Author

Click to run the code above.

@titonobre

titonobre commented Nov 17, 2017 •

Copy link
Copy Markdown

That is because isMultiple can be undefined or null. In those cases it is no possible to infer the specific type of SelectProps.

Use this:

function Select(props: SelectProps) {
    if (props.isMultiple) {
        const { id, onChange } = props;
        onChange(id);
    } else if (props.isMultiple === false) {
        const { id, onChange } = props;
        onChange(id);
    }
}

@styfle

styfle commented Nov 17, 2017

Copy link
Copy Markdown
Author

Thanks! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment