JavaScript doesn't have partial class
and therefore neither does TypeScript, as it would have an effect at runtime and is therefore not aligned with TypeScript's design goals (see TypeScript Design Goal #8, "avoid adding expression-level syntax" and TypeScript Design Non-Goal #6, "provide additional runtime functionality"). There was a suggestion for this at microsoft/TypeScript#563 but it was declined as out of scope: such a feature would need to exist in JavaScript before TypeScript would support it.
Instead of partial class
, you could use monkey patching to add behavior to the Validators
class from Angular. Right now you only seem to be asking about static
methods. Since static
methods are essentially the same as a property on the Validators
class constructor itself, you can just add a dark
property that does what you want. In JavaScript that would look like this:
import { Validators } from '@angular/forms';
Validators.dark = function(color) {
return darkValidator(color);
};
Validators.min(2); // okay
Validators.dark('#FFF'); // okay
In order for this to work in TypeScript, you need to do some declaration merging to convince the compiler that Validators
has a static dark
method. There is an open suggestion at microsoft/TypeScript#2957 to allow some easy way of doing this for the static side of classes (the instance side is a bit easier), but for now the available solution is to declare a namespace
with an exported variable named dark
of the right type:
import { Validators, ValidatorFn } from '@angular/forms';
declare module '@angular/forms' {
export namespace Validators {
export let dark: (this: typeof Validators, color: string) => ValidatorFn;
}
}
Validators.dark = function(color: string): ValidatorFn {
return darkValidator(color);
};
Validators.min(2); // okay
Validators.dark('#FFF'); // okay
The declare module
is module augmentation that lets you add typings to the imported '@angular/forms'
module. We've told the compiler that that the exported value named Validators
is a namespace in addition to being a class constructor. This lets you assign and use Validators.dark()
with no compiler warning.
StackBlitz link to code