Typescript-TDD / ts-auto-mock

Typescript transformer to unlock automatic mock creation for interfaces and classes
https://typescript-tdd.github.io/ts-auto-mock
MIT License
599 stars 16 forks source link

createHydratedMock() should return Required<T> #1494

Open hosswald opened 1 year ago

hosswald commented 1 year ago

Subject of the issue

createHydratedMock() mocks optional properties. The typescript compiler should know about that to avoid having to write unnecessary as any in tests.

Your environment

Expected behavior

    const foo = createHydratedMock<{bar?: string}>() // typeof foo == Required<{bar?: string} == {bar: string}
    const baz: string = foo.bar

Actual behavior

    const foo = createHydratedMock<{bar?: string}>()
    const baz: string = foo.bar // TS2322: Type 'string | undefined' is not assignable to type 'string'.
uittorio commented 11 months ago

Hi @hosswald

Instead of using any could you try using

createHydratedMock<{bar?: string}>() as Required<{bar?: string}

This should prevent you casting to any.

In response of what it should return createHydratedMock.

Required would be slightly incorrect because it doesn't consider nested properties in the object, just the first level.

The purpose of ts-auto-mock was not changing the original type but mutating values. I understand where you are coming from and it something that we could have discuss further if we were actively maintaining the library!!

Happy to see a PR with a proposal!