【问题标题】:Converting a type containing string separated by periods into a nested object type将包含由句点分隔的字符串的类型转换为嵌套对象类型
【发布时间】:2022-01-09 03:49:58
【问题描述】:

我有一些包含用句点分隔的文本的字符串。可以有任意数量的句点,例如:

const stringX = "a.b";
const stringY = "a.b.c.d";

我想使用 TypeScript 来创建一些泛型类型 StringToNestedObject,它接受这样的字符串并输出类型嵌套对象类型,例如:

type TypeX = StringToNestedObject<typeof stringX>;
// TypeX should be: { a: { b: string; } }

type TypeY = StringToNestedObject<typeof stringY>;
// TypeY should be: { a: { b: { c: { d: string; } } } }

对于StringToNestedObject,我能想到的最接近的是:

type StringToNestedObject<S extends string> =
    S extends `${infer T}.${infer U}` ? {
        [T]: StringToNestedObject<U>
    } : {
        [S]: string
    };

[T][S] 实际上不起作用,因为:

类型文字中的计算属性名称必须引用其类型为文字类型或“唯一符号”类型的表达式。(1170)
'T' 仅指一种类型,但在这里用作值。(2693)

Here is a TypeScript playground with the above non-working code.

(我为什么要这样做?IndexedDB key paths 是用句点分隔的字符串,代表这样的嵌套对象。)

【问题讨论】:

  • 这能回答你的问题吗? Property path with template literal types(这不是一个完美的重复,但问题主体和答案似乎都很好地解决了您的要求)
  • 不是直接的,因为那是相反的方向,但可能该代码中的某些内容会帮助我弄清楚...

标签: typescript typescript-generics


【解决方案1】:

好吧,也许我应该在写一个问题之前多玩一点:)

这行得通:

const stringX = "a.b";
const stringY = "a.b.c.d";

type StringToNestedObject<S extends string> =
    S extends `${infer T}.${infer U}` ? {[Key in T]: StringToNestedObject<U>} : {[Key in S]: string};

type TypeX = StringToNestedObject<typeof stringX>;
// TypeX should be: { a: { b: string; } }

type TypeY = StringToNestedObject<typeof stringY>;
// TypeY should be: { a: { b: { c: { d: string; } } } }

Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多