[context] `createContext` function recommendation
The current recommendation for `createContext` has
https://github.com/webcomponents-cg/community-protocols/blob/952f15841a809fec73bbaeed842809a2d88b4deb/proposals/context.md?plain=1#L114-L121
This effectively makes `typeof key` to always be `unknown`.
[Lit's implementation](https://github.com/lit/lit/blob/bd881370b83d366f7654dd510731242a68949a20/packages/context/src/lib/create-context.ts#L54-L56) has
```ts
export function createContext<ValueType, K = unknown>(key: K) {
return key as Context<K, ValueType>;
}
```
which allows taking an type argument for the context key. In order to take advantage of this though, **both** type arguments must be provided. If only `ValueType` is provided, `K` defaults to `unknown` as TypeScript does not do [partial inference of type arguments](https://github.com/microsoft/TypeScript/issues/26242).
Now in practice, I don't think having an explicit `KeyType` be provided to `Context` is quite necessary. The extraction of the `ValueType` does not require it:
https://github.com/webcomponents-cg/community-protocols/blob/952f15841a809fec73bbaeed842809a2d88b4deb/proposals/context.md?plain=1#L101-L104
I'm a bit torn as it feels correct to allow explicitly typing the `KeyType` as in the Lit implementation, but if it's functionally moot, that creates confusion like https://github.com/lit/lit/issues/4601
One issue with having `KeyType` be `unknown` is that it can look confusing. With `unknown & {__context: ValueType}`, it just looks like `{__context: ValueType}` in type intellisense.
e.g.
```ts
const key = Symbol('foo');
const foo = createContext<{foo: string}>(key);
// ^? const foo: {
// __context__: {
// foo: string;
// };
// }
```
3 条评论