首页 > 解决方案 > 打字稿:使用通用函数获取嵌套对象的值

问题描述

我想使用通用函数访问打字稿中嵌套对象的值。

(TL;DR:帖子末尾带有游乐场链接的版本)。

设置

以下设置。我想通过连字 (CSS) 访问图标。另外我想给所有图标一个符号名称,所以同一个图标的连字和符号名称可以不同,例如:

symbolic name: 'home'
ligature     : 'icon-home'

也可以添加自定义图标字体来扩展图标集合。因此必须编辑打字稿。为了防止名称冲突并使这种扩展成为可能,我为图标定义了一个命名空间,名为icon-source.

例如engineicon-source="car"返回调用,用返回engine调用。engineicon-source="airplaine"turbine

我的方法

所以让我们假设有 3 个已定义的图标集,icon-set="standard"默认情况是在哪里。

首先,我定义了一个enum(字符串),其中包括所有可用的图标集。

const enum GlobalIconSources {
    'standard' = 'standard',
    'airplaine' = 'airplaine',
    'car' = 'car',
}

然后我为每个图标集定义另一个enum(字符串)和相应的类型。该类型的键仅限于枚举的字符串。

const enum GlobalIconSourcesStandard {
    'none' = 'none',
    'home' = 'home',
    'power' = 'power',
};

type ListOfStandardIcons = {
    [key in keyof typeof GlobalIconSourcesStandard]: string
}

之后,我定义了一个接口和一个包含所有图标的相应全局对象。

/**
 * Defines interface which includes all icon sources with their types.
 */

interface GlobalIcons {
    [GlobalIconSources.standard]: ListOfStandardIcons,
    [GlobalIconSources.airplaine]: ListOfSource1Icons,
    [GlobalIconSources.car]: ListOfSource2Icons,
}

/**
 * Defines global object in which all used icon names are defined.
 * [symbolic-name] : [css-name/ligature]
 */

const ICONS : GlobalIcons = {
    'standard': {
        'none': '',
        'home': 'icon-home',
        'power': 'icon-power'
    },
    'airplaine': {
        'wing': 'ap-wing',
        'turbine': 'ap-turbine',
        'landing-gear': 'ap-lg',
    },
    'car': {
        'brakes': 'car-brakes',
        'engine': 'car-engine',
        'car-tire': 'car-tire',
    },
};

访问值的函数

然后有以下函数来访问全局对象的值。如果图标/图标源组合存在,该函数应返回图标的值(连字)。否则函数返回undefined

/**
 * Returns the ligature of an icon.
 * @param {map} Global icon object.
 * @param {test} Symbolic icon name.
 * @param {source} Source, where icon is defined.
 * @returns Icon ligature when icon is defined, otherwise undefined.
 */
function getIcon<T extends GlobalIcons, K extends keyof GlobalIcons, S extends keyof T[K]>(map: T, test: unknown, source: Partial<keyof typeof GlobalIconSources> = GlobalIconSources.standard) : T[K] | undefined{
    if(typeof test === 'string' && typeof source === 'string' && typeof map === 'object'){
        if(map.hasOwnProperty(source)){
            const subMap =  map[source as K];
            if(subMap.hasOwnProperty(test)) return subMap[test as S];
        }
    }
    return undefined;
}

这可行,但是:函数的返回类型是ListOfStandardIcons | ListOfSource1Icons | ListOfSource2Icons | undefined(请参阅 ts 游乐场)。我期望string作为返回类型。

假设我用source="standard"and调用函数test=""home。那么泛型应该是:

T       : GlobalIcons
T[K]    : ListOfStandardIcons | ListOfSource1Icons | ListOfSource2Icons (assuming K is keyof T)
T[K][S] : string (assuming K is keyof T and S is keyof T[K]

我知道我要回来了T[K] | undefined。我想返回T[K][S] | undefined,但返回的类型始终是undefined(根据 TS 游乐场)。

任何人都知道如何处理返回类型是子对象ListOfStandardIcons | ListOfSource1Icons | ListOfSource2Icons)的正确类型的函数?

TS游乐场

TypeScript Playground 演示

编辑:设置已更改

我更改了设置并删除了枚举并现在使用对象。

// Defines all available icon sources 
const iconSources = {
    'standard': 'standard',
    'anotherSource': 'anotherSource',
} as const;

// List of icon sources corresponding to the iconSource object
type IconSource = Partial<keyof typeof iconSources>;

// Defines list icon of the "standard" icon source
const StandardIcons = {
    'none': '',
    'home': 'icon-home',
    'power': 'icon-power',
} as const;

// Defines list icon of the "anotherSource" icon source
const Source1Icons = {
    'car': 'my-car',
    'airplaine': 'my-airplaine',
} as const;

// Defines interface and global object
interface Icons {
    [iconSources.standard]: { [key in keyof typeof StandardIcons]: string },
    [iconSources.anotherSource]: { [key in keyof typeof Source1Icons]: string },
}

// Access icon ligatures using icons[iconSourceName][iconKey]
const icons: Icons = {
    'standard': StandardIcons,
    'anotherSource': Source1Icons,
};

我还更改了访问图标源的语法。现在我想传递 1 个参数,即"iconSource/iconName". 当字符串包含 no/时,使用标准图标源。因此,现在需要 1 而不是 2 参数,但此test参数需要unknown输入,因为它是迄今为止尚未验证的用户输入。

/**
 * This function was copied from here: https://fettblog.eu/typescript-hasownproperty/
 */
function hasOwnProperty<X extends {}, Y extends PropertyKey>
  (obj: X, prop: Y): obj is X & Record<Y, unknown> {
  return obj.hasOwnProperty(prop)
}

function getIcon<L extends Icons, Source extends keyof L, Icon extends keyof L[Source]>(list: L, test: unknown): L[Source][Icon] | undefined {
    if(typeof test === 'string'){
        let icon: string = test;
        let source: string = iconSources.standard; // Use the standard icon source, when no source is defined
        if(test.indexOf('/') > -1){
            const splitted = test.split('/');
            source = splitted[0];
            icon = splitted[1];
        }
        // If source is correct
        if(hasOwnProperty(list, source)){
            // If icon is correct return list[source][icon]
            if(hasOwnProperty(list[source as Source], icon)) return list[source as Source][icon as Icon];
        }
    }
    return undefined;
}

但是我遇到了同样的问题,该函数总是返回类型undefined(返回值是正确的)。

// Test
const input1: unknown = 'home';
const input2: unknown = 'standard/none';
const input3: unknown = 'anotherSource/car';
const input4: unknown = 'abc';
const input5: unknown = 'anotherSource/abc';

// Expected results but type of all variables is undefined
const result1 = getIcon(icons, input1); // => 'icon-home' with typeof string
const result2 = getIcon(icons, input2); // => '' with typeof string
const result3 = getIcon(icons, input3); // => 'my-car' with typeof string
const result4 = getIcon(icons, input4); // => undefined 
const result5 = getIcon(icons, input5); // => undefined 

新游乐场

新游乐场

标签: typescripttypescript-generics

解决方案


我的倾向是声明getIcon()为具有多个调用签名的重载函数,这些调用签名对应于调用函数的多种方式。以下是调用签名:

// call signature #1
function getIcon<S extends keyof Icons, I extends string & keyof Icons[S]>(
  list: Icons, test: `${S}/${I}`): Icons[S][I];

test如果您传入包含斜杠 ( /) 字符的参数,将调用第一个调用签名,其中斜杠之前的部分是Icons(编译器从中推断类型参数S)的键,斜杠之后的部分是键of Icons[S](编译器从中推断类型参数I)。这是可能的,因为从TypeScript 4.1 中引入的模板文字类型推断。请注意,为了让编译器对包含在模板文字类型中感到满意,我们还需要约束 此调用的返回类型是.IstringIIcons[S][I]

// call signature #2
function getIcon<I extends keyof Icons['standard']>(
  list: Icons, test: I): Icons['standard'][I];

如果第一个调用签名不是,第二个调用签名将被调用,并且如果您传入一个test参数,该参数是 的键Icons['standard'],编译器从中推断类型参数I。它返回Icons['standard'][I]。此调用签名的行为类似于S参数已指定为的第一个调用签名"standard"

// call signature #3, optional
function getIcon(list: Icons, test: string): undefined;

如果前两个不是,则调用最后一个调用签名,它接受 的任何stringtest,并返回undefined。这是当编译器尝试匹配调用签名但失败时发生的默认行为。从技术上讲,这是您要求的,但我认为最好不要包含此调用签名。

如果您将其注释掉,那么当有人调用时,编译器会警告您调用错误getIcon(icons, "someRandomCrazyString"),而不是允许它并返回。这是静态类型系统吸引力的一部分。在有机会在运行时执行之前捕获此类不需要的代码。undefinedgetIcon()


无论如何,一旦定义了这些调用签名,就可以实现该功能。以下实现与您的实现几乎相同,只是它不需要进行太多运行时检查。如果打电话的人getIcon()正在编写 TypeScript,那么他们会收到警告,例如,如果他们为like传递了一个非string值。在这里进行运行时检查的唯一原因是,如果您担心有人会从未经过类型检查的 JavaScript 代码运行。由你决定:testgetIcon(icons, 123)getIcon()

// implementation
function getIcon(list: any, test: string) {
    let source: string = iconSources.standard
    let icon: string = test;
    if (test.indexOf('/') > -1) {
        const splitted = test.split('/');
        source = splitted[0];
        icon = splitted[1];
    }
    return list[source]?.[icon];
}

所以,让我们测试一下。请注意,如果您不注释iconsand的类型,您会很高兴input1,等等。类型注释(非联合类型)往往会使编译器忘记传入的任何实际值:

const icons = {
    'standard': StandardIcons,
    'anotherSource': Source1Icons,
};
const input1 = 'home';
const input2 = 'standard/none';
const input3 = 'anotherSource/car';
const input4 = 'abc';
const input5 = 'anotherSource/abc';

在这里,编译器知道它input1是字符串文字类型 "home"而不是stringor unknown。如果你注释为stringor unknown,编译器将不知道getIcon()会返回什么,或者不让你调用getIcon()

好的,现在开始测试。getIcon()如果您使用三个呼叫签名进行呼叫,这就是您得到的结果:

const result1 = getIcon(icons, input1); // const result1: string
const result2 = getIcon(icons, input2); // const result2: string
const result3 = getIcon(icons, input3); // const result3: string
const result4 = getIcon(icons, input4); // const result4: undefined
const result5 = getIcon(icons, input5); // const result5: undefined

如果您注释掉第三个,那么这就是您得到的:

const result1 = getIcon(icons, input1); // const result1: string
const result2 = getIcon(icons, input2); // const result2: string
const result3 = getIcon(icons, input3); // const result3: string
const result4 = getIcon(icons, input4); // compiler error!
const result5 = getIcon(icons, input5); // compiler error!

在这两种情况下,编译器都认为input1input2input3是有效输入。在前一种情况下,input4andinput5被接受并undefined返回,而在后一种情况下,input4andinput5用红色波浪线加下划线,并警告您没有getIcon()匹配该调用的过载。

Playground 代码链接


推荐阅读