我有一个数据 struct 来代表我的业务操作:
const operations = {
list: {
request: "a",
response: "b",
},
get: {
request: "a",
response: "b",
},
} as const;
我想创建一个函数,它将接受基于上面operations
的回调:
type Ops = typeof operations;
type Callbacks = {
[Property in keyof Ops]: (
param: Ops[Property]["request"]
) => Ops[Property]["response"];
};
现在,如果我想定义我的回调,如果我错过了其中的任何一个,编译器都会抱怨:
const callbacks: Callbacks = {
};
// ^^^--- Type '{}' is missing the following properties from type 'Callbacks': list, get
现在我的问题是,我想创建另一个类型,以便我可以类型判断operations
对象的 struct :
interface OperationDescriptor<A, B> {
request: A;
response: B;
}
type Operations = {
[key: string]: OperationDescriptor<any, any>;
};
const operations: Operations = {
list: {
request: "a",
response: "b",
},
get: {
request: "a",
response: "b",
},
} as const; // okay
const badOperations: Operations = {
list: {
request: "a",
response: "b",
},
get: { // error, missing response prop
request: "a",
},
} as const;
但当我这样做时,编译器将不再抱怨,因为Operations
不知道我在operations
中的键.有没有办法既有我的蛋糕又吃它,例如:
- 定义一个类型,我可以用它来判断
operations
和 - 有一个
Callbacks
类型会根据operations
的 struct 对我的回调函数进行类型判断?