How do I set the type, for custom store
, when I pass store
via setContext
or component prop?
#6433
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The key is Full answer with example by H.B. - https://stackoverflow.com/a/73543650/2908501 There are two primary options: Use preprocess-svelte and write TypeScript or add JSDoc type annotations. With TS: <script lang="ts">
import { getContext } from 'svelte';
// Prop
export let count: StoreType;
// Context
const store = getContext<StoreType>('context');
</script> With JSDoc: <script>
import { getContext } from 'svelte';
// Prop
/** @type {StoreType} */
export let count;
// Context
/** @type {StoreType} */
const store = getContext('context');
</script> You can declare types in separate .d.ts files or use @typedef. The createCount function can be extracted to a separate file without issue. That way its return type can also be used when typing props/contexts. E.g. // create-count.js
import { writable } from 'svelte/store';
export function createCount() {
const { subscribe, set, update } = writable(0);
return {
subscribe,
increment: () => update(n => n + 1),
decrement: () => update(n => n - 1),
reset: () => set(0),
};
}
<script>
import { getContext } from 'svelte';
/** @type {ReturnType<import('./create-count').createCount>} */
export let count;
/** @type {ReturnType<import('./create-count').createCount>} */
const store = getContext('context');
</script> In TS this is cleaner, since you can just import the type as part of regular code and use type aliases. <script lang="ts">
import type { createCount } from './create-count';
import { getContext } from 'svelte';
export let count: Count;
const store = getContext<Count>('context');
type Count = ReturnType<typeof createCount>;
</script> Originally posted by H.B. in https://stackoverflow.com/a/73543650/2908501 |
Beta Was this translation helpful? Give feedback.
The key is
ReturnType
.Full answer with example by H.B. - https://stackoverflow.com/a/73543650/2908501
There are two primary options: Use preprocess-svelte and write TypeScript or add JSDoc type annotations.
With TS:
With JSDoc:
You can declare types in separate .d.ts files or use @typedef.
The create…