[英]Svelte components with generics
我想在 Svelte(Kit) 組件的道具中使用泛型類型,我發現有這種type T = $$Generic
的東西:
<script lang="ts">
import type { Writable } from "svelte/store";
type T = $$Generic;
export let store: Writable<T[]>;
</script>
雖然這很好,但我確實需要比這更多的信息:我要求T
有一個屬性id
。 通常我會做這樣的事情:
export type WithId = { id: number };
function foo<T extends WithId>(property: T) { ... }
我怎樣才能為 Svelte 組件道具做類似的事情?
您可以像這樣指定它擴展的類型:
type T = $$Generic<{ id: number }>;
您也可以使用type
或interface
名稱,但如果您在組件中定義它們,您可能必須將它們放在模塊腳本中,例如:
<script lang="ts" context="module">
interface WithId { id: number }
</script>
<script lang="ts">
export let store: Writable<T[]>;
type T = $$Generic<WithId>;
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.