Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

Typescript return a function which return a component that has type constraint

Here is my code, but it won't pass typescript validation

import * as React from "react";

export function makeWrapperFn<P, C extends React.ComponentType >(Comp: C, baseProps = {}  ) {
  return (props: Partial<P> = {} ) => {
    // I want this returned function can override the props
    return (<Comp {...baseProps} {...(props)} />);
    // Comp is problem here
  };
}

The error message is:

Type 'Partial<P>' is not assignable to type 'IntrinsicAttributes & LibraryManagedAttributes<C, { children?: ReactNode; }>'.
  Type 'Partial<P>' is not assignable to type 'LibraryManagedAttributes<C, { children?: ReactNode; }>'.ts(2322)

So how do I make this wrapper function maker that with typescript constraint?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Answer in my comment is pretty similar.

But, there is one difference - there is no Partial props.

So I decided to answer, feel free to mark it is as a dublicate.

import * as React from "react";

// If You want to use Partial, please use Partial also in type of Comp

export function makeWrapperFn<P extends object>(Comp: React.ComponentType<Partial<P>>, baseProps = {}  ) {
  return (props: Partial<P>) => {
    // I want this returned function can override the props
    return (<Comp {...baseProps} {...(props)} />);
    // Comp is problem here
  };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...