Skip to content

Commit b8f869d

Browse files
authored
feat: Add PublicInterface type (#197)
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).
1 parent 654f9cf commit b8f869d

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/misc.test-d.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,28 @@
11
import { expectAssignable, expectNotAssignable, expectType } from 'tsd';
22

3-
import type { RuntimeObject } from './misc';
3+
import type { PublicInterface, RuntimeObject } from './misc';
44
import { isObject, hasProperty, getKnownPropertyNames } from './misc';
55

6+
//=============================================================================
7+
// PublicInterface
8+
//=============================================================================
9+
10+
class ClassWithPrivateProperties {
11+
#foo: string;
12+
13+
bar: string;
14+
15+
constructor({ foo, bar }: { foo: string; bar: string }) {
16+
this.#foo = foo;
17+
this.bar = bar;
18+
}
19+
}
20+
21+
// Private properties not required
22+
expectAssignable<PublicInterface<ClassWithPrivateProperties>>({ bar: 'bar' });
23+
// Public properties still required
24+
expectNotAssignable<PublicInterface<ClassWithPrivateProperties>>({});
25+
626
//=============================================================================
727
// isObject
828
//=============================================================================

src/misc.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,15 @@ export type Mutable<
1717
[Key in keyof Omit<ObjectValue, TargetKey>]: ObjectValue[Key];
1818
};
1919

20+
/**
21+
* Get a type representing the public interface of the given type. The
22+
* returned type will have all public properties, but will omit private
23+
* properties.
24+
*
25+
* @template Interface - The interface to return a public representation of.
26+
*/
27+
export type PublicInterface<Interface> = Pick<Interface, keyof Interface>;
28+
2029
/**
2130
* Useful for representing some value that _might_ be present and / or complete.
2231
*

0 commit comments

Comments
 (0)