Rico Kahler
Rico Kahler

Reputation: 19282

How to remove properties from type without emitting JS?

How can I remove properties from a type without emitting js?

I know how to remove a type using object spreads:

interface SomeType {
  one: string,
  two: number,
  foo: Date,
}

let obj: SomeType = {} as any;
const { foo, ...restOfObj } = obj;
type _withoutFoo = typeof restOfObj;

interface SomeTypeWithoutFoo extends _withoutFoo { }

but my issue with that is that it emits unnecessary javascript and it looks kind of confusing to devs who aren't well-versed in typescript or newer javascript features.

Is there a way to pull properties out of a type without using an object spread? Or is there a way to not emit javascript there?

Upvotes: 3

Views: 218

Answers (1)

ariels - IGNORE AI
ariels - IGNORE AI

Reputation: 551

TypeScript 2.8 adds some useful type combinators; you can use Exclude:

interface SomeType {
  one: string,
  two: number,
  foo: Date,
}

type Remove<T, K> = {
    [P in Exclude<keyof T, K>]: T[P];
};

interface SomeTypeWithoutFoo extends Remove<SomeType, 'foo'> { }

function f(stwf: SomeTypeWithoutFoo) { return f; }

f({ one: 'a', two: 2 });

Upvotes: 1

Related Questions