From 311cefa80ba7a58f9bed296ec7805c067358ebe8 Mon Sep 17 00:00:00 2001 From: Mark Stacey Date: Thu, 11 Jul 2024 09:02:59 -0230 Subject: [PATCH] feat: Add PublicInterface type Add a type for deriving the "public interface" of a type, excluding private properties. Excluding private properties can be useful in making our classes more easily testable (types with private properties are more difficult to mock). --- src/misc.test-d.ts | 22 +++++++++++++++++++++- src/misc.ts | 10 ++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/misc.test-d.ts b/src/misc.test-d.ts index 42da5b00e..45623e834 100644 --- a/src/misc.test-d.ts +++ b/src/misc.test-d.ts @@ -1,8 +1,28 @@ import { expectAssignable, expectNotAssignable, expectType } from 'tsd'; -import type { RuntimeObject } from './misc'; +import type { PublicInterface, RuntimeObject } from './misc'; import { isObject, hasProperty, getKnownPropertyNames } from './misc'; +//============================================================================= +// PublicInterface +//============================================================================= + +class ClassWithPrivateProperties { + #foo: string; + + bar: string; + + constructor({ foo, bar }: { foo: string; bar: string }) { + this.#foo = foo; + this.bar = bar; + } +} + +// Private properties not required +expectAssignable>({ bar: 'bar' }); +// Public properties still required +expectNotAssignable>({}); + //============================================================================= // isObject //============================================================================= diff --git a/src/misc.ts b/src/misc.ts index 700d46760..f0e826964 100644 --- a/src/misc.ts +++ b/src/misc.ts @@ -17,6 +17,16 @@ export type Mutable< [Key in keyof Omit]: ObjectValue[Key]; }; + +/** + * Get a type representing the public interface of the given type. The + * returned type will have all public properties, but will omit private + * properties. + * + * @template Interface - The interface to return a public representation of. + */ +export type PublicInterface = Pick; + /** * Useful for representing some value that _might_ be present and / or complete. *