在尝试实例化扩展TypeError的类时,我遇到了一个非常奇怪的react-relay。我用create-react-app my-app --scripts-version=react-scripts-ts创建了一个简单的类型记录项目来演示这个问题。
每当我运行yarn start时,我看到的就是:

这个错误对我来说没有意义:TypeError: Object prototype may only be an Object or null: undefined
我只是尝试实例化我自己的扩展Relay.Mutation类的一个新实例。我真的是新的反应接力世界和ES6/类型记录,所以这很可能是愚蠢的东西,我只是错过了。
在这个简单的项目中,我直接使用DefinitelyTyped存储库中定义的示例类。
难道我不能像这样使用这个类吗?
const atm = new AddTweetMutation({ text: 'asdf', userId: '1123' });下面是AddTweetMutation.tsx类的样子:
import * as Relay from 'react-relay';
interface Props {
text: string;
userId: string;
}
interface State {
}
export default class AddTweetMutation extends Relay.Mutation<Props, State> {
public getMutation() {
return Relay.QL`mutation{addTweet}`;
}
public getFatQuery() {
return Relay.QL`
fragment on AddTweetPayload {
tweetEdge
user
}
`;
}
public getConfigs() {
return [{
type: 'RANGE_ADD',
parentName: 'user',
parentID: this.props.userId,
connectionName: 'tweets',
edgeName: 'tweetEdge',
rangeBehaviors: {
'': 'append',
},
}];
}
public getVariables() {
return this.props;
}
}下面是整个Hello.tsx React组件:
import * as React from 'react';
import AddTweetMutation from '../mutations/AddTweetMutation';
export interface Props {
name: string;
enthusiasmLevel?: number;
}
class Hello extends React.Component<Props, {}> {
render() {
const atm = new AddTweetMutation({ text: 'asdf', userId: '1123' });
console.log(atm);
const { name, enthusiasmLevel = 1 } = this.props;
if (enthusiasmLevel <= 0) {
throw new Error('You could be a little more enthusiastic. :D');
}
return (
<div className="hello">
<div className="greeting">
Hello {name + getExclamationMarks(enthusiasmLevel)}
</div>
</div>
);
}
}
export default Hello;
// helpers
function getExclamationMarks(numChars: number) {
return Array(numChars + 1).join('!');
}这就是我的package.json的样子:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@types/jest": "^20.0.6",
"@types/node": "^8.0.19",
"@types/react": "^16.0.0",
"@types/react-dom": "^15.5.2",
"@types/react-relay": "^0.9.13",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-relay": "^1.1.0",
"react-scripts-ts": "2.5.0"
},
"devDependencies": {},
"scripts": {
"start": "react-scripts-ts start",
"build": "react-scripts-ts build",
"test": "react-scripts-ts test --env=jsdom",
"eject": "react-scripts-ts eject"
}
}更新:这些类型目前不适用于反动继电器> 1.x。请看关于此问题的github线程。我也更新了我的回购与解决办法。
发布于 2017-08-07 06:39:14
问题是react-relay@1.1.0已经改变了它的API,@types/react-relay@0.9.13已经过时了。
TypeScript根据可用的类型(类型定义)静态地分析代码。所以,即使你@types/react-relay@0.9.13已经过时了,TypeScript也不知道,只是基于它行事而已。
要解决这个问题,您可以:
@types/react-relay at https://github.com/DefinitelyTyped/DefinitelyTyped更新其类型@types/react-relay并执行declare module "react-relay"将其标记为any类型(您将失去类型安全性和IDE支持,但如果类型不正确,无论如何也无关紧要)。对于最后一个选项,请执行以下操作:
// custom-typings/react-relay.d.ts
declare module 'react-relay'
// tsconfig.json
{
"include": [
"custom-typings"
]
}https://stackoverflow.com/questions/45535641
复制相似问题