Skip to content

Commit

Permalink
feat: Add PublicInterface type (#197)
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
Gudahtt authored Jul 12, 2024
1 parent 654f9cf commit b8f869d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/misc.test-d.ts
Original file line number Diff line number Diff line change
@@ -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<PublicInterface<ClassWithPrivateProperties>>({ bar: 'bar' });
// Public properties still required
expectNotAssignable<PublicInterface<ClassWithPrivateProperties>>({});

//=============================================================================
// isObject
//=============================================================================
Expand Down
9 changes: 9 additions & 0 deletions src/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ export type Mutable<
[Key in keyof Omit<ObjectValue, TargetKey>]: 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<Interface> = Pick<Interface, keyof Interface>;

/**
* Useful for representing some value that _might_ be present and / or complete.
*
Expand Down

0 comments on commit b8f869d

Please sign in to comment.