I want to create a class in TypeScript, which implements an interface in a way that it is required to have all properties of that interface, even the optional ones, but allows for the optional properties to be undefined
.
This is Required_ish<T>
type would be wider than Required<T>
, but stricter than T
, because it would require me to explicitly list all the properties. However the same values would be assignable to the parameters of Required_ish<T>
and T
.
I've tried this but it seems to do the same thing as Required
:
type Required_ish<T> = T & { [K in keyof T]-?: T[K] | undefined }
The desired properties:
interface Foo {
a: string;
b?: number;
}
class Bar1 implements Foo { a = ''; } // allowed
class Bar2 implements Required_ish<Foo> { a = ''; } // error
class Bar3 implements Required<Foo> { a = ''; } // error
class Bar4 implements Foo { a = ''; b = undefined; } // allowed
class Bar5 implements Required_ish<Foo> { a = ''; b = undefined; } // allowed
class Bar6 implements Required<Foo> { a = ''; b = undefined; } // error
class Bar7 implements Foo { a = ''; b = 0; } // allowed
class Bar8 implements Required_ish<Foo> { a = ''; b = 0; } // allowed
class Bar9 implements Required<Foo> { a = ''; b = 0; } // allowed