Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign object literal to `...` because property `...` is missing in object literal [1] but exists in `...`

Tags:

flowtype

I am new flow and currently working on a project with flow strict. I have a type alias being passed to a class. The snippet can be found here

// @flow strict

export type CustomType = {
  a: string,
  b: boolean,
  c: boolean,
  d: boolean,
  e: boolean
};
let d = true;
let b = true;
let customType:CustomType = {
        d,
        b,
        c: true,
 }

class Custom{
  constructor(customType = {}) {}
}

let custom = new Custom(customType);

When passing the object not all properties customType are present. What is the best fix here?

like image 401
omoabobade Avatar asked May 31 '18 09:05

omoabobade


1 Answers

You could type the keys of the CustomType object as optional:

(Try)

// @flow strict

export type CustomType = {
  a?: string,
  b?: boolean,
  c?: boolean,
  d?: boolean,
  e?: boolean
};
let d = true;
let b = true;
let customType: CustomType = {
        d,
        b,
        c: true,
 }

class Custom{
  constructor(customType: CustomType = {}) {}
}

let custom = new Custom(customType);

Alternatively, you could use $Shape<T>. It lets you only pass the keys you're interested in:

(Try)

// @flow strict

export type CustomType = {
  a: string,
  b: boolean,
  c: boolean,
  d: boolean,
  e: boolean
};
let d = true;
let b = true;
let customType: $Shape<CustomType> = {
        d,
        b,
        c: true,
 }

class Custom{
  constructor(customType: $Shape<CustomType> = {}) {}
}

let custom = new Custom(customType);
like image 94
James Kraus Avatar answered Nov 06 '22 01:11

James Kraus