简体   繁体   English

reactjs + typescript 获取错误:类型“字符串”不可分配给类型“从不”

[英]reactjs + typescript getting error: Type 'string' is not assignable to type 'never'

I am trying to setState with componentDidMount after axios request is fulfilled, I am getting error Type 'string' is not assignable to type 'never'.我试图在 axios 请求完成后使用 componentDidMount 设置状态,我收到错误Type 'string' is not assignable to type 'never'.

Below is the code下面是代码

import * as React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import axios from 'axios';

import {
  updateFilterByCategory,
  UpdateFilterRequest,
} from 'ducks/search/filters/reducer';

import { GlobalState } from 'ducks/rootReducer';
import { APPLY_BTN_TEXT } from '../constants';

interface OwnProps {
  categoryId: string;
}

interface StateFromProps {
  value: string;
}

interface DispatchFromProps {
  updateFilter: (
    categoryId: string,
    value: string | undefined,
  ) => UpdateFilterRequest;
}

export type InputFilterProps = StateFromProps & DispatchFromProps & OwnProps;

export interface InputFilterState {
  value: string;
  dropDownValue: {};
}

export class InputFilter extends React.Component<
  InputFilterProps,
  InputFilterState
> {
  constructor(props) {
    super(props);

    this.state = {
      value: props.value,
      dropDownValue: {dept: [],
      items: [],
      emp: [],
      }
    };
  }

  componentDidMount = (prevProps: StateFromProps) => {
    axios.get("/api/data")
      .then(response=>{
        Object.keys(response["result"]).map((key, value)=>{
          
          this.setState(prevState => {
            let dropDownValue = {...prevState.dropDownValue};
            dropDownValue[key] = value
            return {dropDownValue}
          })
        })
      })
      .catch(error=>{
        console.log(error)
      })
  };

  componentDidUpdate = (prevProps: StateFromProps) => {
    const newValue = this.props.value;
    if (prevProps.value !== newValue) {
      this.setState({ value: newValue || '' });
    }
  };

  onApplyChanges = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (this.state.value) {
      this.props.updateFilter(this.props.categoryId, this.state.value);
    } else {
      this.props.updateFilter(this.props.categoryId, undefined);
    }
  };

  onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {

    this.setState({ value: e.target.value });
  };
  
  render = () => {
    const { categoryId } = this.props;
    return (
      <form
        className="input-section-content form-group"
        onSubmit={this.onApplyChanges}
      >

             <input
             list={categoryId}
             className="form-control dropdown-input"
             name={categoryId}
             id={categoryId}
             onChange={this.onInputChange}
             value={this.state.value}
           />
        <button name={categoryId} className="btn btn-default" type="submit">
          {APPLY_BTN_TEXT}
        </button>
      </form>
    );
  };
}

export const mapStateToProps = (state: GlobalState, ownProps: OwnProps) => {
  const filterState = state.search.filters;
  const value = filterState[state.search.resource]
    ? filterState[state.search.resource][ownProps.categoryId]
    : '';
  return {
    value: value || '',
  };
};

export const mapDispatchToProps = (dispatch: any) =>
  bindActionCreators(
    {
      updateFilter: (categoryId: string, value: string | undefined) =>
        updateFilterByCategory({ categoryId, value }),
    },
    dispatch
  );

export default connect<StateFromProps, DispatchFromProps, OwnProps>(
  mapStateToProps,
  mapDispatchToProps
)(InputFilter);

error log错误日志

#23 59.03 ERROR in /app/static/js/pages/SearchPage/SearchFilter/FilterSection/index.tsx
#23 59.03 ./js/pages/SearchPage/SearchFilter/FilterSection/index.tsx
#23 59.03 [tsl] ERROR in /app/static/js/pages/SearchPage/SearchFilter/FilterSection/index.tsx(48,15)
#23 59.03       TS2322: Type '{ categoryId: string; }' is not assignable to type 'Readonly<Omit<never, "value" | "updateFilter"> & OwnProps>'.
#23 59.03   Property 'categoryId' is incompatible with index signature.
#23 59.03     Type 'string' is not assignable to type 'never'.
#23 59.03  @ ./js/pages/SearchPage/SearchFilter/index.tsx 5:0-44 15:40-53
#23 59.03  @ ./js/pages/SearchPage/index.tsx 11:0-42 88:36-48
#23 59.03  @ ./js/index.tsx 21:0-44 48:69-79
#23 59.03 
#23 59.03 ERROR in /app/static/js/pages/SearchPage/SearchFilter/InputFilter/index.spec.tsx
#23 59.03 [tsl] ERROR in /app/static/js/pages/SearchPage/SearchFilter/InputFilter/index.spec.tsx(31,43)
#23 59.03       TS2786: 'InputFilter' cannot be used as a JSX component.
#23 59.03   Its instance type 'InputFilter' is not a valid JSX element.
#23 59.03     Types of property 'componentDidMount' are incompatible.
#23 59.03       Type '(prevProps: StateFromProps) => void' is not assignable to type '() => void'.
#23 59.03 
#23 59.03 ERROR in /app/static/js/pages/SearchPage/SearchFilter/InputFilter/index.tsx
#23 59.03 ./js/pages/SearchPage/SearchFilter/InputFilter/index.tsx
#23 59.03 [tsl] ERROR in /app/static/js/pages/SearchPage/SearchFilter/InputFilter/index.tsx(54,3)
#23 59.03       TS2416: Property 'componentDidMount' in type 'InputFilter' is not assignable to the same property in base type 'Component<InputFilterProps, InputFilterState, any>'.
#23 59.03   Type '(prevProps: StateFromProps) => void' is not assignable to type '() => void'.
#23 59.03  @ ./js/pages/SearchPage/SearchFilter/FilterSection/index.tsx 9:0-41 19:43-54
#23 59.03  @ ./js/pages/SearchPage/SearchFilter/index.tsx 5:0-44 15:40-53
#23 59.03  @ ./js/pages/SearchPage/index.tsx 11:0-42 88:36-48
#23 59.03  @ ./js/index.tsx 21:0-44 48:69-79
#23 59.03 
#23 59.03 ERROR in /app/static/js/pages/SearchPage/SearchFilter/InputFilter/index.tsx
#23 59.03 ./js/pages/SearchPage/SearchFilter/InputFilter/index.tsx
#23 59.03 [tsl] ERROR in /app/static/js/pages/SearchPage/SearchFilter/InputFilter/index.tsx(138,3)
#23 59.03       TS2345: Argument of type 'typeof InputFilter' is not assignable to parameter of type 'ComponentType<never>'.
#23 59.03   Type 'typeof InputFilter' is not assignable to type 'ComponentClass<never, any>'.
#23 59.03     Construct signature return types 'InputFilter' and 'Component<never, any, any>' are incompatible.
#23 59.03       The types of 'props' are incompatible between these types.
#23 59.03         Type 'Readonly<InputFilterProps> & Readonly<{ children?: ReactNode; }>' is not assignable to type 'never'.
#23 59.03  @ ./js/pages/SearchPage/SearchFilter/FilterSection/index.tsx 9:0-41 19:43-54
#23 59.03  @ ./js/pages/SearchPage/SearchFilter/index.tsx 5:0-44 15:40-53
#23 59.03  @ ./js/pages/SearchPage/index.tsx 11:0-42 88:36-48
#23 59.03  @ ./js/index.tsx 21:0-44 48:69-79
#23 59.03 
#23 59.03 webpack 5.6.0 compiled with 4 errors in 53077 ms
#23 59.38 npm ERR! code ELIFECYCLE
#23 59.38 npm ERR! errno 2
#23 59.38 npm ERR! static@1.0.0 build: `cross-env TS_NODE_PROJECT='tsconfig.webpack.json' webpack --progress --config webpack.prod.ts`
#23 59.38 npm ERR! Exit status 2
#23 59.38 npm ERR! 
#23 59.38 npm ERR! Failed at the static@1.0.0 build script.
#23 59.38 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
#23 59.39 
#23 59.39 npm ERR! A complete log of this run can be found in:
#23 59.39 npm ERR!     /root/.npm/_logs/2021-07-13T07_55_35_192Z-debug.log

Tried looking for answers in Argument of type 'any' is not assignable to type 'never'尝试在“任何”类型的参数中寻找答案不能分配给“从不”类型

Since I am new to react and typescript, couldn't solve it, despite looking for answers in internet.由于我是反应和打字稿的新手,尽管在互联网上寻找答案,但无法解决它。

I observed that if I remove componentDidMount, it builds fine without error.我观察到,如果我删除 componentDidMount,它可以正常构建而不会出错。 and if i remove prevProps: StateFromProps from componentDidMount = (prevProps: StateFromProps) and just keep componentDidMount = () then it works fine as well.如果我从componentDidMount = (prevProps: StateFromProps)删除prevProps: StateFromProps并保留componentDidMount = ()那么它也可以正常工作。

what am I doing wrong?我究竟做错了什么?

Thanks in advance!提前致谢!

You have a lot of issues in your code regardless of your question.不管你的问题是什么,你的代码都有很多问题。

One of them is using axios response incorrectly.其中之一是错误地使用axios响应。

axios.get("/api/data")
      .then(response=>{
        Object.keys(response["result"]).map((key, value)=>{

It seems that you're trying to access result from the request body .您似乎正在尝试从请求body访问result In order to do so, you should access it through response.data.result ;为此,您应该通过response.data.result访问它;

Other than that, the source of the presented problem is coming from the fact that you declared your state interface incorrectly.除此之外,出现的问题的根源在于您错误地声明了状态interface

export interface InputFilterState {
  value: string;
  dropDownValue: {};
}

Asserting {} type for dropDownValue means that this key can only contain EMPTY OBJECT ( never ).dropDownValue断言{}类型意味着此键只能包含 EMPTY OBJECT( never )。 You are trying to access some property in dropDownValue using a string based key ( dropDownValue[key] ).您正在尝试使用基于string的键 ( dropDownValue[key] ) 访问dropDownValue某些属性。 Therefore, TypeScript complains that you can not retrieve a value with a string key from an object which declared as an empty object.因此,TypeScript 抱怨您无法从声明为空对象的对象中检索带有字符串键的值。

In order to declare it accordingly, You can declare the right type of dropDownValue in your interface.为了相应地声明它,您可以在您的界面中声明正确类型的dropDownValue

export interface InputFilterState {
  value: string;
  dropDownValue: {
      value: props.value,
      dropDownValue: {
        dept: [],
        items: [],
        emp: [],
      }
    };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型“string[]”不可分配给类型“never[]”。 Typescript 错误 - Type 'string[]' is not assignable to type 'never[]'. Typescript Error Typescript 错误:类型 'number' 不可分配给类型 'never' - Typescript error:Type 'number' is not assignable to type 'never' Typescript 错误:: 类型“数字”不可分配给类型“从不” - Typescript error :: Type 'number' is not assignable to type 'never' 打字稿类型&#39;字符串&#39;不可分配给类型“错误 - Typescript Type ‘string’ is not assignable to type" error TypeScript 错误:类型“字符串”不可分配给排版类型 - TypeScript error: Type 'string' is not assignable to type for Typography 出现 Typescript 错误:类型“any[]”不可分配给类型“never[]”。 TS2345 - Getting Typescript error: Type 'any[]' is not assignable to type 'never[]'. TS2345 ReactJS Typescript 类型的参数 '{ keyPrefix: string; }' 不可分配给字符串类型的参数 - ReactJS Typescript Argument of type '{ keyPrefix: string; }' is not assignable to parameter of type string 'string' 类型的参数不可分配给 typeScript 中的 'never' 类型的参数 - Argument of type 'string' is not assignable to parameter of type 'never' in typeScript 类型 &#39;string&#39; 不可分配给类型 &#39;never&#39; - Type 'string' is not assignable to type 'never' 无法编辑属性,错误类型“字符串”不可分配给类型“从不”与 TypeScript - Can't edit an attribute, error Type 'string' is not assignable to type 'never' with TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM