Skip to content

Add Public<T> #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 6, 2018
Merged

Add Public<T> #32

merged 1 commit into from
Nov 6, 2018

Conversation

ssonne
Copy link
Contributor

@ssonne ssonne commented Nov 6, 2018

Problem: a class with private members cannot be mocked without bypassing the typechecker.

Solution: Add a type Public<T> that maps only the public members. This makes it easy to get a class's public interface for dependency injection and mocking.

type Public<T> = { [P in keyof T]: T[P] };

export class Foo {
    private _priv = 1;

    public getStr():string {
        return 'abc';
    }
}

// Type '{ getStr(): string; }' is not assignable to type 'Foo'.
//  Property '_priv' is missing in type '{ getStr(): string; }'.
const naiveFake: Foo = {
    getStr(): string {
        return 'def';
    }
}

export type IFoo = Public<Foo>;

// Works!
const fake: IFoo = {
    getStr(): string {
        return 'def';
    }
}

See this comment:
microsoft/TypeScript#18499 (comment)

@pelotom pelotom merged commit 5ed09e6 into pelotom:master Nov 6, 2018
@pelotom
Copy link
Owner

pelotom commented Nov 6, 2018

Thanks!

@ssonne ssonne deleted the ssonne/public-type branch November 6, 2018 23:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants