1

There's plenty of info online on using TypeScript's Pick<T> and Omit<T> to construct types that only have a subset of attributes of some class.

What I've completely failed to find is how to leverage the newly created type to initialize an object of said type from attributes of the initial class.

Consider the following:

class Foo {
  a: string;
  b: number;
  c: string;
}

type FooStrings = Pick<Foo, 'a' | 'c'>;

function getFoos(): Array<Foo> {
  // create/get and return a bunch of Foo objects
}

function parseFoos(foos: Array<Foo>): Array<FooStrings> {
  // ???
} 

What exactly am I supposed to put into parseFoos to do only get FooStrings objects without going

source: Foo;
parsed: FooStrings = {
  a: source.a,
  c: source.c
}

every time? Object.assign seems to be more than happy to add all the missing properties.

1
  • 3
    TypeScript does not exist at runtime. All of the type metadata is erased in transpilation. A Foo is already, structurally, usable everywhere a FooStrings is, so parseFoos can just return foos and satisfy the type checking. Commented Sep 30 at 9:17

1 Answer 1

1

If you want a new object that does not have some of the members of the source object, you can either construct it with only the members you want, or copy the source and remove the members you don't want.

If you want an object that satisfies the type FooStrings, source already does.

Typescript does not have the notion of a type which excludes objects with extra members.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.