我试图识别具有特定属性名称的函数的返回类型,目的是过滤掉任何不具有此返回属性名称的函数。
为了说明这一点,假设我们有以下函数对象:
export const StorageActions = {
addFile: () => ({ type: 'ADD_FILE' }),
deleteFile: () => {
return () => {
return null;
};
},
};
type StorageActionsTypes = typeof StorageActions;
借助 ReturnType,我可以查看哪个函数的返回属性名称为“type”:
为了验证返回属性名称为“type”的函数,我 执行如下操作:
type filteredActions = { [K in keyof StorageActionsTypes]:
keyof ReturnType<StorageActionsTypes[K]> extends ('type') ? 'valid' : 'invalid'};
但结果却出乎意料:
应该是:
interface filteredActions {
addFile: 'valid';
deleteFile: 'invalid';
}
我是否错误地使用了“扩展”?实现这一目标的最佳方法是什么?
最佳答案
问题在于您对从不
的解释。绝不像 PR 中所述:
never
is a subtype of and assignable to every type.
这意味着该类型 type y = 从不扩展 's' ? 'Y' : 'N'
将是 'Y'
,因为 never
是 's'
的子类型。
这里的简单解决方案是不使用 keyof
(对于函数来说,它会返回 never
因此出现上面的问题)
export const StorageActions = {
addFile: () => ({ type: 'ADD_FILE' }),
deleteFile: () => {
return () => {
return null;
};
},
};
type StorageActionsTypes = typeof StorageActions
type filteredActions = {
[K in keyof StorageActionsTypes]:
ReturnType<StorageActionsTypes[K]> extends { type: any } ? 'valid' : 'invalid'
}; // now { addFile: "valid"; deleteFile: "invalid"; }
关于typescript - 提取函数的返回类型并按 typescript 中的属性名称进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53854442/