'Use decorator on class with argument to restrict properties

As the question, would like to know if there's any approach that could have the class decorator restrict the decorated class properties based on the decorator argument in typescript.


code snippet

decorator:

type Exactly<T, U extends { [key in keyof T]: any }> = { [K in keyof U]: K extends keyof T ? any : never };

function DefinePolicy<K>(infer: K) {
  return function<TCtor extends Exactly<K, TCtor>>(cls: TCtor): TCtor {
    return cls;
  };
}

class:

export class ResouceOne {
  name: string;

  age: number;
}

@DefinePolicy(ResouceOne)
export class ResoureOnePolicy {
  name: 'foo';

  age: 20;

  incorrect: 'SHOULD GET ERROR';
}

type check:

type TypeCheck = ResoureOnePolicy extends Exactly<ResouceOne, ResoureOnePolicy>? true: false;

// type TypeCheck = false

So I did receive false from above type check, but seems like it doesn't really work in the inner function of decorator when there's unexpected property got defined in the decorated class.

How can we have the decorator capture the type error in the first? any advice would be appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source