Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ts 有办法在编译阶段限制 react 子组件的参数类型吗

比如有一个 Form 组件,它需要所有子组件都有 name 字段

<Form>
    <Input name="username"></Input>
    <Select name="sex"></Select>
    
    // 这里写的时候会报错,因为没有 name 字段
    <div></div>
</Form>

还有就是form可以限制子组件参数的类型,比如:

interface IUserSchema {
    username: string
    sex: 1 | 2
}

<Form schema={IUserSchema}>
    <Input name="username"></Input>
    <Select name="sex"></Select>
    
    // 这里写的时候会报错,因为没有 age 字段
    <Input name="age"></Input>
</Form>

注意,以上都需要在编译阶段就过不了

interface IProps {
  children?: // 这里的类型需要怎么写才能实现上面的需求呢? 
}

export const Form: FunctionComponent<IProps> = ({ children }) => {
  return <form>{children}</form>
}

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

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...