Skip to content

Instantly share code, notes, and snippets.

@styfle
Created November 17, 2017 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save styfle/58973dbe558cd7052242bdf2b4cc4b17 to your computer and use it in GitHub Desktop.
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
Copy link
Author

styfle commented Nov 17, 2017

Thanks! 🎉

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