Цель состоит в том, что один разработчик определяет отображение типов ответов/запросов. Другой разработчик реализует функцию, и, учитывая тип запроса, TypeScript должен помочь ему понять, какой ожидаемый тип ответа, не рассматривая отображение печати. Это возможно?// Define the request types
interface SetKittenPenRequest {
action: 'set-kitten-pen';
count: number;
}
interface GetPuppyRequest {
action: 'get-puppy';
id: string;
}
// Define the response types
interface SetKittenPenResponse {
success: boolean;
msg: string;
}
interface GetPuppyResponse {
success: boolean;
details: { breed: string; age: number };
}
// Create a union type for the requests
type CuteReq = SetKittenPenRequest | GetPuppyRequest;
// Define a ResponseMap where each action maps to a response type
type CuteResMap = {
'set-kitten-pen': SetKittenPenResponse;
'get-puppy': GetPuppyResponse;
};
// Simple function declaration for the message listener
function handleCuteReqs(
message: T,
sendResponse: (response: CuteResMap[T['action']]) => void
) {
if (message.action === 'set-kitten-pen') {
const response: SetKittenPenResponse = {
success: true,
msg: `Kitten pen set for ${message.count} kittens!`,
};
sendResponse(response);
} else if (message.action === 'get-puppy') {
const response: GetPuppyResponse = {
success: true,
details: { breed: 'Golden Retriever', age: 2 },
};
sendResponse(response);
}
}
< /code>
Но это дает < /p>
Argument of type 'SetKittenPenResponse' is not assignable to parameter of type 'CuteResMap[T["action"]]'.
Type 'SetKittenPenResponse' is not assignable to type 'SetKittenPenResponse & GetPuppyResponse'.
Property 'details' is missing in type 'SetKittenPenResponse' but required in type 'GetPuppyResponse'.ts(2345)
Подробнее здесь: https://stackoverflow.com/questions/796 ... typescript