6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Svelteで型安全かつキーが不要になったcreateContextが追加されました!

Last updated at Posted at 2025-11-30

Svelte 5.40.0 で createContext が追加されました。
型安全に Context を扱え、さらにキーを自分で管理する必要がなくなっています。
従来の Context と比較しながら紹介します。

今までの書き方

従来の Svelte の Context は、setContextgetContext を使って値を受け渡す仕組みでした。

<!-- Parent.svelte -->
<script>
  import { setContext } from 'svelte';
  
  setContext('my-key', { name: 'Kazuma' });
</script>
<!-- Child.svelte -->
<script>
  import { getContext } from 'svelte';
  
  const user = getContext('my-key');
</script>

<p>こんにちは {user.name} さん!</p>

しかしこの方法には、いくつかの扱いづらいポイントがあります。

  • キー(文字列、Symbol、オブジェクト)を自分で定義して管理する必要がある
  • キーの共有漏れや衝突が起こりうる
  • TypeScript では型が保証されない

そのため、型安全に使いたい場合はラッパーコードを自作する必要がありました。

import { getContext, setContext } from 'svelte';

type User = {
  id: number;
  name: string;
  email: string;
};

const key = {};

export function setUserContext(user: User) {
  setContext(key, user);
}

export function getUserContext() {
  return getContext(key) as User;
}

このようにすれば型は付けられますが、キー管理やキャスト記述など、少し煩雑になります。

これからの書き方

Svelte 5.40.0 からは、上記のような自作ラッパーやキー管理が不要になります。
createContext を使うと、キー生成から型付けまで Svelte が面倒を見てくれるため、少ないコードで安全に扱えます。

// context.ts
import { createContext } from 'svelte';

type User = {
  id: number;
  name: string;
  email: string;
};

export const [getUserContext, setUserContext] = createContext<User>();
  • 自前のキー定義がいらない
  • 戻り値が自動で適切な型になる
  • 余計なキャストやラッパー関数を作らなくてよい
  • Context 定義ファイルが最低限で済む

といったメリットがありますので皆さんSvelte 5.40.0にアップデートして書き換えましょう!

6
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?