我在 .tsx 文件中使用 Typescript 和 Material-ui 编写 ReactJS 类。在我的自定义组件之一中,我想创建对我在自定义组件中使用的组件之一的引用。
export class MyTextField extends React.Component<MyProps, MyState> {
private refTextField: React.RefObject<TextField>;
constructor(props: MyProps) {
super(props);
this.refTextField = React.createRef();
}
render(): JSX.Element {
const { id, label, value: defaultValue } = this.props;
const { value } = this.state;
const element = (
<TextField ref={this.refTextField} id={id} label={label} defaultValue={defaultValue} value={value} />
);
return element;
}
}
Run Code Online (Sandbox Code Playgroud)
在编译期间,我在引用的声明中收到错误消息:
'TextField' 指的是一个值,但在这里被用作一种类型。TS2749
我试图将“typeof TextField”放在我的声明中,但在我的渲染中评估 ref 属性时,我有另一条消息:
类型 'RefObject<(props: TextFieldProps) => Element>' 不能分配给类型 '((instance: HTMLDivElement | null) => void) …
在 TypeScript 中,我声明了一个这样的接口:
export default interface MyDTO {
readonly num: string;
readonly entitle: string;
readonly trb: string;
readonly ucr: string;
readonly dcr: string;
readonly udm?: string;
readonly ddm?: string;
}
Run Code Online (Sandbox Code Playgroud)
使用函数,我想访问属性的值,该属性的名称包含在变量中。
private doSomething(dto: MyDTO, property: string): any {
let label: any;
if (['dcr', 'ddm'].includes(property)) {
label = doSomethingElse(dto[property]);
} else {
label = dto[property];
}
return label;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,TypeScript 给了我以下错误消息:
元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 'MyDTO'。在类型“MyDTO”.ts(7053) 上找不到带有“字符串”类型参数的索引签名
有人有想法吗?
谢谢
在声明我的接口之后,我在使用 ESLint 和 Typescript 时遇到了一些问题,尤其是在分号上。此外,我使用 VSCode 作为编辑器,并在保存时自动格式化。
这是我的配置文件 .eslintrc.json:
{
// "parser": "babel-eslint",
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint", "babel", "standard"],
"parserOptions": {
"ecmaVersion": 2017,
"sourceType": "module"
},
"env": {
"es6": true,
"browser": true,
"amd": true,
"node": true,
"jest": true
},
"globals": {},
// "extends": ["eslint:recommended"],
"extends": ["plugin:@typescript-eslint/recommended"],
"rules": {
"array-bracket-spacing": ["error", "never", {}],
"brace-style": "error",
"camelcase": ["error", { "properties": "never" }],
"comma-dangle": [
"error",
{
"arrays": "never",
"objects": "never",
"imports": "never",
"exports": "never",
"functions": "never"
}
],
"comma-spacing": ["error", { "before": …
Run Code Online (Sandbox Code Playgroud) typescript ×3
eslint ×1
interface ×1
javascript ×1
material-ui ×1
reactjs ×1
tsx ×1
validation ×1