3 ms·
You can use an `in` check for this, since TypeScript version 2.7 [0]. Here's an example (Playground link: [1]): import * as React from 'react' type P
by bcherny 7y ago
You can use an `in` check for this, since TypeScript version 2.7 [0].
Here's an example (Playground link: [1]):
import * as React from 'react'
type Props =
| {a: number}
| {b: string}
function MyComponent(props: Props): JSX.Element {
if ('a' in props) {
return <div>a is {props.a}</div>
}
return <div>b is {props.b}</div>
}
let x = <MyComponent a={3} />
let y = <MyComponent b="foo" />
[0] https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#type-guards-inferred-from--in-operator https://www.typescriptlang.org/docs/handbook/release-notes/t...
[1] https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQFA0wCeYWcACsWOgLw1x9wAfOAG9kALjgA7AK4gARligBfXvyHC5E1DCjBJAcxU0C0yfmARJcALIMAwiUiSskmAAowHVBPYROASgkAKQBlAA0AOgBRABssEBd4YVVgAjg3MmQyOD04Tz9UfxFVPkoYaSgrAB4AE2AANwA+ZBz0YXzOCOQlKoB6OqbVFVKscsq4WobGuVaRDtQIuR7+qZojOPgADzguCdsHcEtElC5hAGYlOF7Gmg24Bh29+0cj1zg5LgAiAggIT6ubkA https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLg...
- danenania 7y agoOh nice! I’ll give that a try, thanks.