0

I have an external type that comes from the library:

type Anything = Record<string, any>; 

I want to override it and not allow usage of a specific key c.

Results that I want to achieve:

type CustomAnything = Anything & { c?: never } // This is what I was able to come to, but it does not completely forbid the usage of the `c`. Undefined is allowed in this case

const a: CustomAnything = { a: 1, b: 2} // OK
const b: CustomAnything = { a: 1, c: undefined } // Error, because I want to prevent the use of `c` key 
const c: CustomAnything = { a: 1, c: 2 } // Error, because I want to prevent the use of `c` key 
const d: CustomAnything = { a: 1} // OK

Here is a playground. Any ideas how to achieve this?

mr__brainwash
  • 1,334
  • 3
  • 16
  • 40
  • I'm not 100% sure what the expected result is supposed to be in your example. What do you mean by restrict? Are you just trying to get rid of the property c? – Braks Jul 26 '21 at 17:06
  • Please consider modifying this question to be explicit about what you are trying to do and what you consider the problem to be, and ideally include any code as text in the question in addition to the external link. If your problem is "I don't want to allow `undefined` as a value when a property is optional", then this is probably a duplicate of [this question](https://stackoverflow.com/questions/54489817/typescript-partialt-type-without-undefined). If your problem is something else, could you spell it out? Thanks! – jcalz Jul 26 '21 at 19:33
  • I updated the question, hope it is clear now – mr__brainwash Jul 27 '21 at 06:59
  • @mr__brainwash doesn't `type CustomAnything = Anything & { c: never }` already work? (Notice that I removed the question mark from the c property) – Braks Jul 27 '21 at 07:06
  • Unfortunately, no. Variable names are underlines in this case: ```Type '{ a: number; b: number; }' is not assignable to type 'CustomAnything'. Property 'c' is missing in type '{ a: number; b: number; }' but required in type '{ c: never; }'``` – mr__brainwash Jul 27 '21 at 07:41

1 Answers1

0

Use the Omit utility type

type CustomAnything = Omit<Anything, 'c'>

Omit:

Constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).

LCIII
  • 3,102
  • 3
  • 26
  • 43