相关疑难解决方法(0)

打字稿:嵌套对象的深度键

所以我想找到一种方法来拥有嵌套对象的所有键。

我有一个在参数中采用类型的泛型类型。我的目标是获取给定类型的所有键。

在这种情况下,以下代码运行良好。但是当我开始使用嵌套对象时,情况就不同了。

type SimpleObjectType = {
  a: string;
  b: string;
};

// works well for a simple object
type MyGenericType<T extends object> = {
  keys: Array<keyof T>;
};

const test: MyGenericType<SimpleObjectType> = {
  keys: ['a'];
}
Run Code Online (Sandbox Code Playgroud)

这是我想要实现的目标,但它不起作用。

type NestedObjectType = {
  a: string;
  b: string;
  nest: {
    c: string;
  };
  otherNest: {
    c: string;
  };
};

type MyGenericType<T extends object> = {
  keys: Array<keyof T>;
};

// won't works => Type 'string' is not assignable to type 'a' | …
Run Code Online (Sandbox Code Playgroud)

typescript

31
推荐指数
5
解决办法
1万
查看次数

Typescript:嵌套对象的深层 keyof,具有相关类型

我正在寻找一种拥有嵌套对象的所有键/值对的方法。

(用于 MongoDB 点符号键/值类型的自动完成)

interface IPerson {
    name: string;
    age: number;
    contact: {
        address: string;
        visitDate: Date;
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我想要实现的目标,使其成为:

type TPerson = {
    name: string;
    age: number;
    contact: { address: string; visitDate: Date; }
    "contact.address": string;
    "contact.visitDate": Date;
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

在这个答案中,我可以得到密钥Leaves<IPerson>。于是就变成了'name' | 'age' | 'contact.address' | 'contact.visitDate'

在 @jcalz 的另一个答案中,我可以通过DeepIndex<IPerson, ...>.

是否有可能将它们组合在一起,成为类似的类型TPerson

修改 9/14:用例,需要和不需要:

当我开始这个问题时,我在想它可以像这样简单[K in keyof T]: T[K];,只需进行一些巧妙的转换。但是我错了。这是我需要的:

1. 索引签名

所以界面

interface IPerson { …
Run Code Online (Sandbox Code Playgroud)

javascript mongodb mongodb-query typescript typescript-generics

15
推荐指数
2
解决办法
8990
查看次数

将函数返回值定义为读取对象中路径的类型

我想创建一个简单的辅助函数来从对象中读取路径,如下所示:

interface Human {
  address: {
    city: {
      name: string;
    }
  }
}

const human: Human = { address: { city: { name: "Town"}}};
getIn<Human>(human, "address.city.name"); // Returns "Town"
Run Code Online (Sandbox Code Playgroud)

这个帮助器在 JS 中很容易创建,但在 TS 中使其类型安全有点复杂。我已经做到了这一点:

type Prev = [never, 0, 1, 2, 3, 4, 5, 6, ...0[]];

type Join<K, P> = K extends string | number
  ? P extends string | number
    ? `${K}${"" extends P ? "" : "."}${P}`
    : never
  : never;

type Path<T, D extends number = 4> …
Run Code Online (Sandbox Code Playgroud)

typescript typescript-generics typescript-typings

2
推荐指数
1
解决办法
793
查看次数