在阅读了这个教程之后,我注意到clickOutside
函数返回一个带有destroy
方法的对象。
自定义use
指令的正确返回类型是什么?
export function clickOutside(node: HTMLElement): ??? {
// setup work goes here...
return {
destroy() {
// ...cleanup goes here
}
};
}
这是一个ActionReturn
export interface ActionReturn<Parameter = any> {
update?: (parameter: Parameter) => void;
destroy?: () => void;
}
来自import type { ActionReturn } from "svelte/types/runtime/action";
但是我建议使用Action
类型而不是ActionReturn
:
import type { Action } from "svelte/types/runtime/action";
const clickOutside: Action<HTMLElement, undefined> = (node) => {
// setup work goes here...
return {
destroy() {
// ...cleanup goes here
}
};
};
因为这样可以让Typescript验证动作的options参数的类型和update方法的类型是相同的。
自3.46.6
以来导入路径已更改。
- 4.0.0: Action和ActionReturn更严格的类型(参见PR的迁移说明)(#7442)
- 3.46.6:在已发布包中实际包含动作TypeScript接口(#7407)
- 3.46.5:为键入动作添加TypeScript接口(#6538)
现在应该从svelte/action
导入。参考v4文档。
<script>
/** @type {import('svelte/action').Action} */
function foo(node) {
// the node has been mounted in the DOM
return {
destroy() {
// the node has been removed from the DOM
},
};
}
</script>
<div use:foo />