Typescript 中的动态类型分配问题

问题描述 投票:0回答:1

从其他文件导入以下资源,由于所有权限制(我不拥有它)无法更改:

    //otherfile.ts
    //============
    export type Maybe<T> = T | null;
    export type Scalars = {
      ID: string;
      String: string;
      Int: number;
      AWSDateTime: any;
    };
        export interface SortOption {
          label: string;
          order: "asc" | "desc";
          key: string;
          id: string;
        }
        export type Asset = {
          typename?: 'Asset';
          updated_by?: Maybe<Scalars['String']>;
          license_plate?: Maybe<Scalars['Int']>;
          length?: Maybe<Scalars['Int']>;
        }
        export const SORT_OPTIONS: SortOption[] = [
          {
            order: "desc",
            key: "updated_date",
            label:"A",
            id:"A"
          },
        ]

这是消费上面的代码。我拥有此代码,可以自由更改此处的任何内容。

//consumer.ts
//===========
    //import the above stuff here
    import { sortBy } from "lodash";
    type SortOptionKey = keyof typeof SORT_OPTIONS[number]["key"] | string;
    
    export const getSortedAssetsByOrder = (
      assets: Asset[],
      key:  SortOptionKey,
      order?: boolean | "asc" | "desc"
    ) => {
      return sortBy(assets, (x) => x[key || ""] || "").reverse();
    };

在 x[key || 的最后一行出现错误""] 部分,如果我用这样的硬编码类型测试它:

  key:  "updated_date" | "lst_evnt_t",//SortOptionKey,

错误消失了

Element 隐含地具有“any”类型,因为类型的表达式 “SortOptionKey”不能用于索引类型“资产”。无索引 在 type

上找到参数类型为“string”的签名

我在 consumer.ts 中有哪些选项可以解决这个问题?

typescript typescript-typings react-typescript
1个回答
0
投票

虽然缺少一些细节,但问题是

SortOptionKey
keyof Asset
是不同的东西。
SortOptionKey
可能有一些
Asset
中不存在的值,因此,您应该接受
Asset
中的值。只需将
key
类型修改为

即可
key: SortOptionKey & keyof Asset

相当于

SortOptionKey
keyof Asset

的相互作用
© www.soinside.com 2019 - 2024. All rights reserved.