AlexGilleran / jsx-control-statements

Neater If and For for React JSX
https://www.npmjs.com/package/babel-plugin-jsx-control-statements
MIT License
1.62k stars 64 forks source link

The control statements don't narrow TypeScript types #105

Closed slikts closed 2 years ago

slikts commented 3 years ago

The JSX control statements don't work in TypeScript the same as other conditional operators, because they don't narrow the types. Code example:

declare const Foo: (props: { bar: string }) => JSX.Element
declare const bar: string | null

// No error
bar ? <Foo bar={bar} /> : null
// Error: Type 'string | null' is not assignable to type 'string'.
(<If condition={!!bar}><Foo bar={bar} /></If>)

The <If> example should semantically be the same as the ternary condition example, since that's what it compiles to, but it throws an error because the type of bar is not narrowed down to just string and instead stays as string | null.

texttechne commented 2 years ago

Yes, this is known:

☠️ Beware: This is a Babel plugin. It changes your code to other code - this means that some tooling that looks at your code (e.g. static analysis, typescript) is likely to not work. This plugin dates back to when JSX was daring and Javascript was more like playdough than meccano - if you want to stay on the well-trodden path stick with writing && and map.

Unfortunately this library cannot fix this problem: On the one hand you need a transformer to make this work on the code level with React, but on the other hand the typescript compiler will not know about this transformation, so it will complain. Try out: TSX-Control-Statements

@AlexGilleran As TS has become so popular, it's probably worth to point this out more clearly