我想定义我的自定义组件,并指定哪种";标准部件";我想延期。
这将为扩展组件的所有标准属性使用VSCode intellisense,而无需重新定义所有属性。
这就是我想做的:
<script lang="ts">
// Error: Cannot redeclare block-scoped variable '$$props'
export let $$props: svelte.JSX.HTMLAttributes<HTMLButtonElement>;
// OR
// Error: Cannot redeclare block-scoped variable '$$restProps'
export let $$restProps: svelte.JSX.HTMLAttributes<HTMLButtonElement>;
export let myCustomProp: string;
</script>
<button {...$$restProps}>{myCustomProp}<slot /></button>
为了更好地解释我想做什么,我在React with Typescript 中发布了同样的案例
import React from 'react';
type Props = {
myCustomProp: string;
} & React.ButtonHTMLAttributes<HTMLButtonElement>;
export default function ({ myCustomProp, ...rest }: Props) {
return (
<button {...rest}>
{myCustomProp}
{rest.children}
</button>
);
}
使用svelte/elements
提供一个扩展要键入的特定HTML元素的interface $$Props
。
Button.svelte
:
<script lang="ts">
import type { HTMLButtonAttributes } from 'svelte/elements'
interface $$Props extends HTMLButtonAttributes {
myCustomProp: string
}
export let myCustomProp: string
</script>
<button {...$$restProps}>
{myCustomProp}
<slot />
</button>
+page.svelte
:
<script lang="ts">
import Button from './Button.svelte'
let disabled = false
</script>
<Button myCustomProp='foo' {disabled}>Click Me</Button>
编辑:如果你正在处理更复杂的类型,你可以在导出的道具中使用你在$$Props
中定义的类型:
export let myCustomProp: $$Props["myCustomProp"]