我一直在用TypeScript重构我们的一些React应用程序,遇到了一个障碍,我不得不解决,在我看来,一个非常丑陋的双类型参数.这是TypeScript中的一个bug,还是我遗漏了一些类型歧义,导致回调参数默认为"any"类型?
我通过将原始类型隐藏到另一个类型参数中来解决这个问题,这似乎修复了回调方法从"extends string"条件推断错误类型.
原代码:
type Optional<TItem> = TItem extends string
? { get?: (item: TItem) => string }
: { get: (item: TItem) => string };
type TItem = { hello: string } | string;
const obj: Optional<TItem> = {
get: item => typeof item === 'string' ? item : item.hello
};
原始代码从npx tsc
开始的输出(打字5.4.2):
error TS7006: Parameter 'item' implicitly has an 'any' type.
18 get: item => typeof item === 'string' ? item : item.hello
解决方法:
type TItem = { hello: string } | string;
type Optional<TItem, TItemType> = TItemType extends string
? { get?: (item: TItem) => string }
: { get: (item: TItem) => string };
const obj: Optional<TItem, TItem> = {
get: item => typeof item === 'string' ? item : item.hello
};