简体   繁体   中英

type with Maybe props doesn't allow type with Non-Maybe props

Why does flow throw errors here?

type MaybeProp = {
  prop: ?number,
}

type DefinetlyProp = {
  prop: number,
}


const requireMaybe = (u: MaybeProp) => console.log(u)
const requireDefinetly = (u: DefinetlyProp) => requireMaybe(u)

https://flow.org/try/#0FDAuE8AcFMAIFkCG4BG0AKAnA9pWBeWAb2Flkh0gC5YB+AOwFcBbNTAGmAF8QIZYAItABmAS3rRQAG3BZcBYqXKUaTVtA7cQwAMbZ6AZ1CxM0AI6NRppKjiEAFIxo20cyAEoCAPlh7D2KWgAOilsAHNHd119IxNzS1MhMQlpcAVHGiTxSRk3T3wfUwsraBdoSKA

It seems like that a function, that can handle maybe properties, should also be able to handle the same properties when they are definetly defined.

Any way to work around this?

This is because objects in JS are mutable. As far as the type system is concerned, requireMaybe could execute u.prop = null . Then, the original caller would be expecting prop to be a number , but it would actually be null . This would break type safety.

You can accomplish what you want to by using property variance :

type MaybeProp = {
  +prop: ?number,
}

type DefinetlyProp = {
  +prop: number,
}


const requireMaybe = (u: MaybeProp) => console.log(u)
const requireDefinetly = (u: DefinetlyProp) => requireMaybe(u)

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