1

Is it possible to create a type constraint such that a type contains non optional keys of an object but not all keys? For example:

class Foo {
  key1: number
  key2: Object
  key3: <other type>
}

const X = {
  key1: 'foo'
  key2: 'bar'
  foo: // compilation error
}

So in this model X has a subset of keys of Foo, and compile time checks against non existing keys. Basically Partial<Foo> but unlike Partial<Foo> I want it such that if someone references X.key3 it will fail to compile because key3 is not defined on X. Is this possible?

devshorts
  • 8,572
  • 4
  • 50
  • 73
  • Dont know if I got that right, can you clarify a little. Maybe add a example of what you want to be able to do and what you want to fail – Patrick Hollweck Oct 03 '19 at 19:34
  • I see syntax errors in your object assigned to `X`, but as your example is not indicating that `const X: Foo = {`, there is no type checks on `X`. – crashmstr Oct 03 '19 at 19:53
  • Yes. It will be cumbersome and you'll probably not want it though. :) https://stackoverflow.com/questions/49580725/is-it-possible-to-restrict-typescript-object-to-contain-only-properties-defined However, for object literals it works by default and out of box. See "excess property checks": https://www.typescriptlang.org/docs/handbook/interfaces.html – sbat Oct 04 '19 at 12:14

1 Answers1

0

If I understand your question right: You want a type that is a subset of another type and all properties on the new type should be required.

Does the following work for you?

class Foo {
  key1?: number;
  key2?: Object;
  key3?: string;
};

type Bar = Required<Pick<Foo, 'key1' | 'key2'>>;

const bar: Bar = {
  key1: 3,
  key2: {},
};


Explanation:

  • Pick a subset of keys from another type with Pick<T, 'prop1' | 'prop2' | ...>
  • Make all properties of a type required with Required<T>
a1300
  • 2,633
  • 2
  • 14
  • 18