第一次使用TS设置React, Next js应用程序并获得成功。
TS抛出redux-saga
setup:
属性'name'在类型'Input | DataPostGreeting | ErrorPostGreeting'上不存在。属性'name'在类型'DataPostGreeting'上不存在
准确地说,name
在成功响应类型DataPostGreeting
上不存在,但在Input
上存在
该操作是一个POST,用于在测试应用程序上创建问候语。
我认为我已经正确地键入有效载荷为Input
,这是问候的name
,但TS似乎对此并不满意。尽管它确实将Input
识别为适用类型的一部分。
这是带有突出显示的错误触发器的传奇:
/store/sagas/greetings.ts
import { all, call, put, takeLatest } from 'redux-saga/effects';
import { actionPostGreetingOk, actionPostGreetingError } from '../actions/creators';
import { Actions } from '../actions/names';
import { ActionTypes } from '../actions/types';
import { apiQl } from 'lib/functions';
function* postGreeting(action: ActionTypes) {
const queryQl = `mutation createGreeting(
$name: String!
) {
createGreeting(input: {
name: $name
}) {
greeting {
id
}
}
}`;
const variables = {
name: action.payload.name, // *** ERROR IS THROWN HERE ***
};
try {
const data = yield call(apiQl, queryQl, variables);
if (data.errors) {
yield put(
actionPostGreetingError({
error: data.errors,
}),
);
} else {
yield put(
actionPostGreetingOk({
greeting: data.data.createGreeting,
}),
);
}
} catch (error) {
if (error.response === undefined || error.code === 'ECONNABORTED') {
console.log('ERROR RESPONSE UNDEFINED, ABORTED');
}
}
export default function* greeting() {
yield all([takeLatest(Actions.POST_GREETING, postGreeting)]);
}
关于types文件:
...
export interface Input {
name: string;
}
export interface ActionPostGreeting {
type: typeof Actions.POST_GREETING;
payload: Input;
}
...
export type ActionTypes =
| ActionPostGreeting
| ActionPostGreetingInit
| ActionPostGreetingOk
| ActionPostGreetingError
| ActionHydrate;
动作创建者:
export const actionPostGreeting = (payload: Input): ActionPostGreeting => {
return {
type: Actions.POST_GREETING,
payload,
};
};
您将整个ActionTypes
联合传递给您的saga,但您的函数应该只采用特定的有效载荷类型(例如ActionPostGreeting
)。否则,这意味着您的saga可以与任何有效负载一起调用,为了解决您的问题,您可以像这样限制类型:
function* postGreeting(action: ActionPostGreeting) {
// do stuff
const variables = {
name: action.payload.name, // will be good
};
}