Is there a way to use svelte getContext etc. svelte functions in Typescript files?

Viewed 619
1 Answers

You can use getContext inside TypeScript files, but you can only call it during initialization of the component - that is, the first time the contents of the component's script tag are run.

// TS code
import { getContext } from 'svelte';

export function getFooContext() {
  const foo = getContext('foo');
}

export function fails() {
  setTimeout(() => getFooContext(), 100);
}

// Svelte code
<script>
  import { getFooContext } from './somewhere';
  
  // this is ok
  getFooContext();
  // this fails because it's called after the component is initialized
  setTimeout(() => getFooContext(), 100);
  // this fails because the function has a setTimout which is resolved
  // after the component is initialized
  fails();
</script>

You cannot call getContext or setContext or any of Svelte's lifecycle functions outside of the component initialization, which means you can't call it

  • asynchronously (for example after a timeout)
  • in reaction to a DOM event of the component
  • etc
Related