Thibaud Rouchon
Thibaud Rouchon

Reputation: 40

How to create a partial type that return an error if too much information are given

I would like to create a type that can accept a partial object but that can also return an error if we give to that object extra properties.

I tried that but it doesn't work like i want.

type Object = {
  a: string;
  b: string;
  c: string;
};

const fn = <T extends Partial<Object>>(param: T) => {
  console.log(param);
};

//should be ok and is ok
fn({ a: "a" });

//should be ok and is ok
fn({ a: "a", b: "b" });

//should not be ok BUT is ok 
fn({ a: "a", b: "b", d: "d" });

Upvotes: 0

Views: 62

Answers (2)

geoffrey
geoffrey

Reputation: 2454

It looks like excess property checking doesn't work on the constraint of a generic. If you need that generic, you can replicate it manually with a mapped type

const fn = <T extends { [K in keyof T]: K extends keyof Object ? T[K] : `the key '${K & string}' does not exist in Object` }>(param: T) => {
  console.log(param);
};

playground

Upvotes: 0

cefn
cefn

Reputation: 3341

How does this look?

const fn = (
  props: {
    [k in "a" | "b" | "c"]?: string;
  }
) => {
  console.log(props);
};

//should be ok and is ok
fn({ a: "a" });

//should be ok and is ok
fn({ a: "a", b: "b" });

//should not be ok AND is not ok
fn({ a: "a", b: "b", d: "d" });

Upvotes: 0

Related Questions