peakchen90 / babel-plugin-react-directives

A babel plugin that provides some directives for react(JSX), similar to directives of vue.
https://peakchen90.github.io/babel-plugin-react-directives
MIT License
96 stars 13 forks source link

TypeScript does not understand x-if #31

Open smtchahal opened 2 years ago

smtchahal commented 2 years ago

Describe the bug TypeScript does not understand x-if. Inside an x-if block, the passed variable should be evaluated for truthyiness, but it is not.

To Reproduce Steps to reproduce the behavior:

The following code should do it:

type MyNameProps = {
    children: string
}

const MyName = ({ children }: MyNameProps) => (
    <div>{children}</div>
)

type MyComponentProps = {
    name: string | null
}

const MyComponent = ({ name }: MyComponentProps) => (
    <MyName x-if={name}>{name}</MyName>
)
// ...

Expected behavior TypeScript compiles successfully and does not show any errors. {name} gets passed as a string to <MyName>.

Actual behavior TypeScript complains that <MyName> requires children to be of type string, but string | null was passed.

Environment

peakchen90 commented 2 years ago

@smtchahal Please replace type MyComponentProps with:

type MyComponentProps = {
    name: string
}

And it will work fine!

smtchahal commented 2 years ago

@peakchen90 Of course it will, but the point is, sometimes the requirements are such that the type just needs to be nullable or optional. When that's the case, the following will work fine with TypeScript:

const MyComponent = ({ name }: MyComponentProps) => (
    <>
        name && <MyName>{name}</MyName>
    </>
)

If this is okay with TypeScript, then x-if should also be okay.

peakchen90 commented 2 years ago

@smtchahal I mean this has nothing to do with x-if , it's the default behavior of Typescript

peakchen90 commented 2 years ago

@smtchahal Oh, I understand, but maybe I cannot do something for it... It just a babel plugin