What is the solution to disallow a method from accepting a parameter of type keyof this
where the property is nullable?
Consider the following example:
abstract class MyAbstractClass {
get<K extends keyof this>(key: K): this[K] {
return this[key];
}
getOptional<K extends keyof this>(key: K, defaultValue: this[K]): this[K] {
return this[key] || defaultValue;
}
}
class MyClass extends MyAbstractClass {
foo: string = "ok";
bar: number = 4;
baz: boolean = true;
optional?: {} = {};
}
const instance = new MyClass();
const yepItsAString: string = instance.get("foo"); // Ok
const yepItsOpitional: {} = instance.get("optional"); // <!= this should not work
For the code sample and more information, visit the codesandbox