Joseph Fraley
Joseph Fraley

Reputation: 1400

How can I type a default export using Flow?

How can I type a default export using Flow? Does Flow have a way of accomplishing this?

Desired Outcome:

// index.js
type complexThing = {
  a: string
}
type Thing = {
  x: number,
  y: boolean,
  z: complexThing
}

export default {
 x: 0,
 y: true,
 z: {a: 'hello'}
} : Thing // this says my default export is a Thing

Acceptable Alternative:

Alternatively, I wouldn't mind typing each of the object properties inline, but I think that's syntactically impossible:

export default {
 // I don't know how to add type signatures here
 x: 0, // number
 y: true, // boolean
 z: {a: 'hello'} // complexThing
}

Not What I Want:

What I don't want to do is store a variable just to to Flow type it:

// index.js
type complexThing = {
  a: string
}
type Thing = {
  x: number,
  y: boolean,
  z: complexThing
}

const myThing: Thing = {
 x: 0,
 y: true,
 z: {a: 'hello'}
}

export default myThing

Upvotes: 18

Views: 4691

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161457

You are doing a typecast so you will need parens around the object, e.g. change

export default {
  x: 0,
  y: true,
  z: {a: 'hello'}
} : Thing

to

export default ({
  x: 0,
  y: true,
  z: {a: 'hello'}
} : Thing)

Upvotes: 14

Related Questions