Created
November 17, 2017 15:04
-
-
Save styfle/58973dbe558cd7052242bdf2b4cc4b17 to your computer and use it in GitHub Desktop.
TypeScript SO question 41705559
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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);
}
}
Thanks! 🎉
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Click to run the code above.