SystemicPlural
SystemicPlural

Reputation: 5789

If I have a partial type for a builder. How do I then type it when complete?

How do I use types when I want to build an object?

EG. If I have:

interface Foo {
  a: string;
  b: string;
  c: string;
  d: string;
}

interface Bar extends Partial<Foo>{}

const foo: Foo = useMemo(() => {
  const bar: Bar = {}
  bar.a = 'a';
  bar.b = 'b';
  bar.c = 'c';
  return bar;
,[])

only this results in a type error:

Type 'Partial<Foo>' is not assignable to type 'Foo'.
  Types of property 'a' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not a

Upvotes: 0

Views: 113

Answers (1)

brunnerh
brunnerh

Reputation: 184622

If the properties are complex to create, i would recommend storing them in locals first and then returning the correct type directly:

interface Foo {
  a: string;
  b: string;
  c: string;
  d: string;
}

const foo: Foo = useMemo(() => {
  const a = 'a';
  const b = 'b';
  const c = 'c';
  const d = 'd';

  return { a, b, c, d };
},[])

Upvotes: 2

Related Questions