diff --git a/apps/svelte.dev/content/docs/svelte/06-runtime/02-context.md b/apps/svelte.dev/content/docs/svelte/06-runtime/02-context.md index 95beb916f4..8016a58a80 100644 --- a/apps/svelte.dev/content/docs/svelte/06-runtime/02-context.md +++ b/apps/svelte.dev/content/docs/svelte/06-runtime/02-context.md @@ -84,27 +84,18 @@ Svelte will warn you if you get it wrong. ## Type-safe context -A useful pattern is to wrap the calls to `setContext` and `getContext` inside helper functions that let you preserve type safety: +As an alternative to using `setContext` and `getContext` directly, you can use them via `createContext`. This gives you type safety and makes it unnecessary to use a key: -```js -/// file: context.js +```ts +/// file: context.ts // @filename: ambient.d.ts interface User {} -// @filename: index.js +// @filename: index.ts // ---cut--- -import { getContext, setContext } from 'svelte'; - -const key = {}; - -/** @param {User} user */ -export function setUserContext(user) { - setContext(key, user); -} +import { createContext } from 'svelte'; -export function getUserContext() { - return /** @type {User} */ (getContext(key)); -} +export const [getUserContext, setUserContext] = createContext(); ``` ## Replacing global state diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md b/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md index ea895a9198..92abc36f93 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md @@ -224,8 +224,16 @@ function beforeUpdate(fn: () => void): void; ## createContext +
+ +Available since 5.40.0 + +
+ Returns a `[get, set]` pair of functions for working with context in a type-safe way. +`get` will throw an error if no parent component called `set`. +
```dts @@ -365,6 +373,8 @@ function getAllContexts< Retrieves the context that belongs to the closest parent component with the specified `key`. Must be called during component initialisation. +[`createContext`](/docs/svelte/svelte#createContext) is a type-safe alternative. +
```dts @@ -502,6 +512,8 @@ and returns that object. The context is then available to children of the compon Like lifecycle functions, this must be called during component initialisation. +[`createContext`](/docs/svelte/svelte#createContext) is a type-safe alternative. +
```dts