svelte-typed-context

1.0.1 • Public • Published

Svelte Typed Context

The library provides an interface called InjectionKey which when provided to getContext or setContext allows for stricter types.

It also re-exports getContext and setContext with types made to work with InjectionKey.

Usage

For the best experience, enable strict mode in your tsconfig.json

// in key
import type { InjectionKey } from "svelte-typed-context"

export const key : InjectionKey<{ foo: number }> = Symbol('Desired type')

// in provider component
import { setContext } from "svelte-typed-context"
import { key } from "./key"


setContext(key, "bob") // bad -> would error out
setContext(key, { foo: 123 }) // good -> would work

// in consumer component
import { getContext } from "svelte-typed-context"
import { key } from "./key"

const contextValue = getContext(key) // automatically inferred as { foo: number }

Credits

Inspired by Vue.

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.1
    28
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.1
    28
  • 1.0.0
    1

Package Sidebar

Install

npm i svelte-typed-context

Weekly Downloads

29

Version

1.0.1

License

ISC

Unpacked Size

1.78 kB

Total Files

3

Last publish

Collaborators

  • kamenkolev