首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型记录:使用泛型函数获取嵌套对象的值

类型记录:使用泛型函数获取嵌套对象的值
EN

Stack Overflow用户
提问于 2021-09-14 17:23:15
回答 2查看 900关注 0票数 3

我希望使用泛型函数访问类型记录中嵌套对象的值。

(TL;DR:版本,并在帖子末尾连结至操场)。

设置

跟踪设置。我想通过他们的链接(CSS)访问图标。此外,我还想给所有图标一个符号名,因此相同图标的拼图和符号名称可以不同,例如:

代码语言:javascript
复制
symbolic name: 'home'
ligature     : 'icon-home'

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

例如,:用icon-source="car"调用engine返回engine,用icon-source="airplaine"调用engine返回turbine

我的方法

因此,让我们假设有3个已定义的图标集,其中icon-set="standard"是默认情况。

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

代码语言:javascript
复制
const enum GlobalIconSources {
    'standard' = 'standard',
    'airplaine' = 'airplaine',
    'car' = 'car',
}

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

代码语言:javascript
复制
const enum GlobalIconSourcesStandard {
    'none' = 'none',
    'home' = 'home',
    'power' = 'power',
};

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

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

代码语言:javascript
复制
/**
 * 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

代码语言:javascript
复制
/**
 * 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"test=""home调用函数。那么,泛型应该是:

代码语言:javascript
复制
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游乐场演示

编辑:设置已更改

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

代码语言:javascript
复制
// 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,
};

此外,我还更改了访问图标源的语法。现在我想传递一个参数,即"iconSource/iconName"。当字符串不包含/时,将使用标准图标源。因此,现在需要的不是2个参数,而是1,但是这个test参数需要输入unknown,因为它是一个用户输入,到目前为止还没有被验证。

代码语言:javascript
复制
/**
 * 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类型(返回的值是正确的)相同。

代码语言:javascript
复制
// 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 

新游乐场

新游乐场

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-09-17 23:30:09

我在这里倾向于将getIcon()声明为一个过载函数,具有与调用该函数的多种方法相对应的多个调用签名。以下是呼叫签名:

代码语言:javascript
复制
// 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),而斜杠后面的部分是Icons[S]的键(编译器从中推断类型参数I)。由于模板文字类型在TypeScript 4.1中引入的推论,这是可能的。注意,我们还需要约束 I to string,以便编译器乐于在模板文字类型中包含I。此调用的返回类型为Icons[S][I]

代码语言:javascript
复制
// 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"

代码语言:javascript
复制
// call signature #3, optional
function getIcon(list: Icons, test: string): undefined;

如果前两个调用签名没有调用,则调用最后一个调用签名,并且它接受任何string值用于test,并返回undefined。这是编译器尝试匹配调用签名但失败时发生的默认行为。这在技术上是你要求的,但我认为最好不要包括这个电话签名。

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

无论如何,一旦定义了这些调用签名,就可以实现该函数。下面的实现与您的实现基本相同,只是它不需要做太多的运行时检查。如果调用getIcon()的人正在编写TypeScript,那么如果他们为test (如getIcon(icons, 123) )传入一个非string值,则会受到警告。在这里进行运行时检查的唯一原因是,您是否担心有人会从尚未被键入的JavaScript代码中运行JavaScript。这取决于你:

代码语言:javascript
复制
// 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];
}

所以,让我们来检验一下。请注意,如果不注解 iconsinput1等类型,那么您会感到最开心。类型注释(非友联市类型)往往会使编译器忘记传入的任何实际值:

代码语言:javascript
复制
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",而不是stringunknown。如果注释为stringunknown,编译器将不知道getIcon()将返回什么,或者不允许调用getIcon()

好了,现在开始测试。如果您使用三个调用签名调用getIcon(),您将得到以下结果:

代码语言:javascript
复制
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

如果您将第三条注释掉,那么您将得到以下结果:

代码语言:javascript
复制
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是有效的输入。在前一种情况下,input4input5被接受,undefined被返回,而在后一种情况下,input4input5用红色标记下划线,并且警告您,getIcon()的重载与该调用不匹配。

操场链接到代码

票数 1
EN

Stack Overflow用户

发布于 2021-09-14 18:20:45

您所需要做的就是重载您的功能:

代码语言:javascript
复制
console.clear();

/**
 * Defines all available icon sources.
 */

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

/**
 * Defines standard icons with corresponding type.
 */

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

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

/**
 * Defines custom icons with corresponding type.
 */

const enum GlobalIconSourcesSource1 {
    'wing' = 'wing',
    'turbine' = 'turbine',
    'landing-gear' = 'landing',
};

type ListOfSource1Icons = {
    [key in keyof typeof GlobalIconSourcesSource1]: string
}

/**
 * Defines more custom icons with corresponding type.
 */

const enum GlobalIconSourcesSource2 {
    'brakes' = 'brakes',
    'engine' = 'engine',
    'car-tire' = 'car-tire',
};

type ListOfSource2Icons = {
    [key in keyof typeof GlobalIconSourcesSource2]: 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 = {
    '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',
    },
} as const;


const hasProperty = <Obj, Prop extends string>(obj: Obj, prop: Prop)
    : obj is Obj & Record<Prop, unknown> =>
    Object.prototype.hasOwnProperty.call(obj, prop);

function getIcon<
    IconMap extends GlobalIcons,
    Source extends keyof IconMap,
    Test extends keyof IconMap[Source],
    >(map: IconMap, test: Test, source: Source): IconMap[Source][Test]
function getIcon<
    IconMap extends GlobalIcons,
    Source extends keyof IconMap,
    Test extends keyof IconMap[Source],
    >(map: IconMap, test: Test, source: Source) {
    if (typeof test === 'string' && typeof source === 'string' && typeof map === 'object') {
        if (hasProperty(map, source)) {
            return map[source][test]
        }
    }

    return undefined;
}

// Test
const a = getIcon(ICONS, 'home', 'standard');  // => "icon-home"
const b = getIcon(ICONS, 'turbine', 'airplaine'); // => ap-turbine
const c = getIcon(ICONS, 'engine', 'car');     // => 'car-engine'

console.log(a);
console.log(b);
console.log(c);

游乐场

我使用as const for ICONS来推断整个对象。如果不允许使用as const,则需要传递文字对象作为参数而不是引用。

顺便说一句,您可能根本不想使用hasProperty,因为只允许使用文字参数。

在我的博客中,您可以找到更多关于函数参数推理的信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69182106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档