使用适当的键TypeScript键入字符串或对象

yjghlzjz  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(181)

我的languageSchema可以是一个字符串或带有'Etc'键的对象。我有一个接口:

let getLanguageSchema = (language: string): string => languagesSchemas[language];

interface IReduxProps {
    languageSchema:
        string
        | {
              Etc: {
                  listEmpty: string;
              };
          };
}

组件:

let EmptyList: React.FC<IReduxProps> = (props) => {
    let { languageSchema } = props;

    return (
        <div className="mt-5 text-center grey">
            <i className="now-ui-icons files_paper fs-4" />
            <h3 className="mb-0">{languageSchema.Etc.listEmpty}</h3>
        </div>
    );
};

let mapStateToProps = (state: IReduxState): IReduxProps => ({
    languageSchema: getLanguageSchema(state.common.language),
});

TypeScript compiler说道:'属性'Etc'在类型'string '上不存在|{ Etc:{ listEmpty:string; };}'。 类型“string”上不存在属性“Etc”。
为可以是对象或字符串的属性设置适当类型的正确方法是什么?

cmssoen2

cmssoen21#

有一个可能解决这个问题的解决方案是

  • IReduxProps属性只接受字符串
  • 然后将变量转换为字符串,然后将其解析为对象JSON.parse(JSON.stringify(languageSchema))

接口:

let getLanguageSchema = (language: string): string => languagesSchemas[language];

 interface IReduxProps {
    languageSchema: string 
 }

组件

const EmptyList: React.FC<IReduxProps> = (props) => {
  const { languageSchema } = props;

  const laanguageSchemaObjectType: { Etc: { listEmpty: string } } = JSON.parse(JSON.stringify(languageSchema));

  return (
    <div className="mt-5 text-center grey">
      <i className="now-ui-icons files_paper fs-4" />
      <h3 className="mb-0">{laanguageSchemaObjectType.Etc.listEmpty}</h3>
    </div>
  );
};

const mapStateToProps = (state: IReduxState): IReduxProps => ({
  languageSchema: getLanguageSchema(state.common.language),
});

相关问题