简体   繁体   中英

In React with flowtype how do I type only certain props and allow any others

I'm making an input in form and want to type certain props for my input component but allow any others through without typing them - like all the attributes for an input field.

Do I really need to create a type for all of them?

Flow supports subtype polymorphism. So if you define a type like this

type Foo = {
  a: number,
  b: string,
}

Any object that has at least those fields, will be a valid Foo :

let foo: Foo = { 
    a: 0,
    b: "hello",
    c: false // this is ok
}

However, if you actually need to access those fields then you should make them part of the type.

You can define an intersection type of custom props + any input props:

type Props = {
  foo: string,
  bar: number,
} & $Shape<HTMLInputElement>

$Shape used above:

Copies the shape of the type supplied, but marks every field optional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM