从其他文件导入以下资源,由于所有权限制(我不拥有它)无法更改:
//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 中有哪些选项可以解决这个问题?
虽然缺少一些细节,但问题是
SortOptionKey
和keyof Asset
是不同的东西。 SortOptionKey
可能有一些Asset
中不存在的值,因此,您应该接受Asset
中的值。只需将key
类型修改为即可
key: SortOptionKey & keyof Asset
相当于
SortOptionKey
和keyof Asset
的相互作用