[英]Typescript - return type that is part of whole interface (check if it implements other interface)
I have a generic reducer that's return type is TableState.我有一个返回类型为 TableState 的通用减速器。
const reducerFactory = ..... = (): TableState => ....
TableState:表状态:
interface TableState {
filters: Filter;
data: TableData;
isLoading: boolean;
}
Each component's that uses this reducer factory implements TableState.使用这个 reducer 工厂的每个组件都实现了TableState。 For example
例如
interface SalesReportState implements TableState {
someCommonField: string;
}
App build fails as the types don't match.应用程序构建失败,因为类型不匹配。 I could do
someCommonField?: string;
我可以做
someCommonField?: string;
but someCommonField should be obligatory.但 someCommonField 应该是强制性的。
Is there a Typescript feature that the return type just checks if the table type implements Table State?是否有 Typescript 功能,返回类型只检查表类型是否实现了表状态? So the return type would be some type that makes sure it is an instance of TableState, not exactly TableState type.
因此,返回类型将是确保它是 TableState 实例的某种类型,而不是完全 TableState 类型。
If you want to know if an object implements TableState
, you can use:如果你想知道一个对象是否实现了
TableState
,你可以使用:
if (obj instanceof TableState) // returns true if object implements TableState
only works with abstract class仅适用于抽象类
let obj = {}; // an object you want to check
/**
* A discriminator is a property which determines if the object in question is
* a TableState
*/
function isTableState(obj: any): obj is TableState {
return obj &&
obj.filter &&
obj.data &&
obj.isLoading && typeof(obj.isLoading) === 'boolean';
}
// check phase
if (isTableState(obj)) {
// object is automatically casted to TableState
}
PS: If you want to extend an interface with another interface, use extends
EDIT: I don't know the Filter
and TableData
type, is that an interface or a class? PS:如果你想用另一个接口扩展一个接口,使用
extends
编辑:我不知道Filter
和TableData
类型,这是一个接口还是一个类? The answer may change again, depending on the type答案可能会再次更改,具体取决于类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.