【发布时间】:2021-11-25 03:15:32
【问题描述】:
我一直在尝试为我的方法提出一个泛型类型,并将该类型限制为具有以下要求的对象。
下面是我正在使用的函数。然而,这个函数是在 React 应用程序的自定义钩子中使用的。
function useCustomHook<T>(initialData: T[]) {
const [changes, setChanges] = React.useState<T[]>([])
// calling the method inside the hook with an element should be retrieved from changes
doSomething()
}
function doSomething<T>(obj: T) {
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value)
})
}
// Type
type ExampleType = {
property1: number,
property2: string
}
// Interface
interface ExampleInterface {
property1: number;
property2: string;
}
它应该为以下示例抛出错误(基本上它不应该接受任何原始类型,如字符串、数字、布尔值、null、未定义......):
doSomething('test')
doSomething(12)
doSomething(undefined)
它应该接受以下示例:
doSomething({})
doSomething({ property1: 12, property2: 'string'})
doSomething<ExampleType>({ property1: 12, property2: 'string'})
doSomething<ExampleInterface>({property1: 12, property2: 'string'})
我已经尝试过像这样更改方法:
函数 doSomething
它适用于大多数示例(意味着它会引发错误),但在使用接口时它不起作用(抛出索引签名缺失)。将现有接口更改为类型不是解决方案,我认为如果示例函数是库的一部分,我作为库的用户希望同时拥有接口和类型这两个选项。
但是,如果我将 unknown 更改为 any 但我相信在 Typescript 中应该避免使用 any。
如果有任何建议,我将不胜感激。我相信一定有办法实现它。这里是沙盒:https://codesandbox.io/s/sweet-wildflower-hqr1t
【问题讨论】:
标签: typescript react-hooks typescript-generics