Skip to content
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

fix(types): disambiguate SanityClient imports #445

Merged
merged 1 commit into from
Dec 7, 2023

Conversation

stipsan
Copy link
Member

@stipsan stipsan commented Dec 7, 2023

In the JS world these two are the same instance:

import {SanityClient} from '@sanity/client'
import {SanityClient as SanityCoreClient} from '@sanity/client/stega'

assert(SanityClient === SanityCoreClient) // all good

But due to how we generate typings, TypeScript thinks they're not compatible as they're classes with private properties:

import type {SanityClient, SanityStegaClient} from '@sanity/client/stega'

interface Props {
  client: SanityClient | SanityStegaClient
}
function Component(props: Props) {}

// Later on
import {createClient} from '@sanity/client'
<Component client={createClient()} />

But now it'll throw an error like:

Argument of type 'import("@sanity/client/dist/index").SanityClient' is not assignable to parameter of type 'import("@sanity/client/dist/stega").SanityClient'.
  Property '#private' in type 'SanityClient' refers to a different member that cannot be accessed from within type 'SanityClient'.ts(2345)

Errors are usually not as clear as the above btw, it took me a while to figure out what was wrong when I first encountered this. The fix is not obvious:

-import type {SanityClient, SanityStegaClient} from '@sanity/client/stega'
+import type {SanityClient} from '@sanity/client'
+import type {SanityStegaClient} from '@sanity/client/stega'

So the point of this PR is that if you now do this:

import type {SanityClient} from '@sanity/client'

You'll get a clear error:

Argument of type 'SanityStegaClient' is not assignable to parameter of type 'never'.ts(2345)

And the import uses a @deprecated symbol to make sure VS Code don't autocomplete it, and clearly highlights it:
image

@stipsan stipsan marked this pull request as ready for review December 7, 2023 13:45
@stipsan stipsan merged commit b4b9079 into main Dec 7, 2023
14 checks passed
@stipsan stipsan deleted the disambiguate-SanityClient-type branch December 7, 2023 13:49
@ecospark ecospark bot mentioned this pull request Dec 7, 2023
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Dec 15, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant