我目前正在研究一种类型安全的方法来声明一个接口,该接口声明一个函数应该如何返回一个对象。该对象应始终包含相同的功能。接口声明如下:
import { DrawingMode } from '@/Pages/Planning/PlanningTypes'
import { Ref } from 'vue'
interface toggleable {
reenable: () => void
disable: () => void
}
interface createableByDraw {
startDrawing: (drawingMode: DrawingMode) => void
onCreated: (layer: L.Layer, drawingMode: DrawingMode) => void
}
export interface LeafletConnectionHookReturnObject
extends toggleable,
createableByDraw {}
export type LeafletConnectionHook = (
currentMap: Ref<L.Map | undefined>
) => LeafletConnectionHookReturnObject
函数是这样实现的:
export const useMappedXY: LeafletConnectionHook = (
currentMap: Ref<L.Map | undefined>
) => {
const onCreated = (layer: L.Layer) => {
}
const startDrawing = () => {
}
const reenable = (anyStringThatShouldNotBeAllowed: string) => {
}
const disable = () => {
}
return {
reenable,
disable,
startDrawing,
onCreated,
}
}
如您所见,“onCreated”和“startDrawing”都没有正确实现接口。 “重新启用”功能甚至需要一个与界面建议的参数完全不同的参数。 当我在任何其他地方使用我的 useMappedXY 函数时,typescript 期望 reenable 函数正确实现接口。为什么会这样,我该怎么做才能正确执行接口?
如果我这样重写我的函数:
export const useMappedXY: LeafletConnectionHook = (
currentMap: Ref<L.Map | undefined>
) => {
const onCreated = (layer: L.Layer) => {
}
const startDrawing = () => {
}
const reenable = (anyStringThatShouldNotBeAllowed: string) => {
}
const disable = () => {
}
const returnObject = {
reenable,
disable,
startDrawing,
onCreated,
}
return returnObject
}
然后打字稿确实正确地推断出 returnObject 没有正确实现接口。但这对我来说似乎很容易被利用并且容易出错