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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That is because
isMultiple
can beundefined
ornull
. In those cases it is no possible to infer the specific type ofSelectProps
.Use this: