TS1131和TS1128在2个常数之间存在差异



在代码中,我发现这部分在ts编译器中运行良好。

export const AbsPro: <State, Action>(props: ComponentProps<State, Action> & { children?: React.ReactNode })
=> React.ReactElement<any> = (props) => {
const { r, s, m, c} = props.store;
return (
<context.Provider value={useStore(r, s, m)}>
{props.children}
</context.Provider>
);
};

现在我想尝试用sono大括号重写这个代码更多:

export const Aa:<State, Action>(props: ComponentProps<State, Action> & { children?: React.ReactNode })=>{
return React.ReactElement=(props)=>{ //line 164
return (<div></div>)//line 165
}
}

但是编译器说我

错误:(164,5(TS1131:需要属性或签名。

错误:(167,1(TS1128:需要声明或语句。

如果我删除第164行之前的大括号并返回第164行,编译器工作正常,但现在我无法理解语法

export const Aa:<State, Action>(props: ComponentProps<State, Action> & { children?: React.ReactNode })=>
React.ReactElement=(props)=>{
return (<div></div>)
}

有人可以帮助我理解为什么编译器不能识别大括号并返回正确的大括号?你能帮我找到关于这个语法的文档吗?

这是因为React.ReactElement是函数的返回类型。您正在定义const的类型,它是一个接受props并返回React.ReactElement的函数。不能执行return React.ReactElement = (props) => {,因为return用于运行时,React.ReactElement用于TS编译时。

您的代码:

export const AbsPro: <State, Action>(props: ComponentProps<State, Action> & { children?: React.ReactNode })
=> React.ReactElement<any> = (props) => {
const { r, s, m, c} = props.store;
return (
<context.Provider value={useStore(r, s, m)}>
{props.children}
</context.Provider>
);
};

可以这样重写(可读性更强的类型(:

type AbsProFn = <State, Action>(props: ComponentProps<State, Action> & { children?: React.ReactNode }) => React.ReactElement<any>;
export const AbsPro: AbsProFn = (props) => {
const { r, s, m, c} = props.store;
return (
<context.Provider value={useStore(r, s, m)}>
{props.children}
</context.Provider>
);
};

export const AbsPro = <State, Action>(props: ComponentProps<State, Action> & { children?: React.ReactNode }): React.ReactElement<any> => {
const { r, s, m, c} = props.store;
return (
<context.Provider value={useStore(r, s, m)}>
{props.children}
</context.Provider>
);
};

如果你愿意,安装了大多数@types/react,你也可以做:

export const AbsPro = <State, Action>(props: React.PropsWithChildren<ComponentProps<State, Action>>): React.ReactElement<any> => {
const { r, s, m, c} = props.store;
return (
<context.Provider value={useStore(r, s, m)}>
{props.children}
</context.Provider>
);
};

通常我更喜欢返回JSX.Element,甚至有时它可能太通用了。此外,我更喜欢使用提升函数而不是常量,因为它们更可读。

export function AbsPro<State, Action> (props: React.PropsWithChildren<ComponentProps<State, Action>>): React.ReactElement<any> {
const { r, s, m, c} = props.store;
return (
<context.Provider value={useStore(r, s, m)}>
{props.children}
</context.Provider>
);
};

无论如何,我仍然看到一个问题:ComponentPropsGeneric,我认为它是一个React类型,只接受一个泛型,而不接受两个。可能与最近的CCD_ 10有关。你应该检查一下,因为我不知道你想用它实现什么。

我为您创建了一个代码沙箱,以便一起查看示例:https://codesandbox.io/s/peaceful-moon-ev3jl

遗憾的是,代码是以我不喜欢的方式自动格式化的,我不知道这是否可以禁用。

相关内容

最新更新