打字稿中具有通用键的对象

die*_*ing 5 javascript typescript typescript-generics typescript-typings

我想创建一个通用函数,它将接受一个对象,然后进行一些转换并返回具有相同键和不同值的新对象。我试图使它成为“强类型”,因此使用它的每个人都将受益于 TS 并且不存在的键应该抛出错误。

我现在所拥有的:

const hash = {
  "first": 1,
  "second": 2,
  "third": 3,
}

type Mapper<T> = {
  [key in keyof T]: number
}

type Result<T>= {
  [key in keyof T]: () => number
}

const transform = <T>(mapper: Mapper<T>) => {
  const result = {} as Result<T>

  (Object.keys(mapper) as (keyof T)[]).map(key => {
    result[key] = () => mapper[key]
  })

  return result
}

type Hash = typeof hash

const a = transform<Hash>(hash)

a.first()
// a.fifth() OK error
Run Code Online (Sandbox Code Playgroud)

它运作良好,但我正在寻找解决方案来解决这个问题:

  1. 删除类型断言 const result = {} as Result<T>

  2. 删除类型断言(Object.keys(mapper) as (keyof T)[])(或使用Object.entries,但在这种情况下似乎也需要类型断言)

我可以在 Typescript 中以更“干净”的方式实现相同的功能吗?

fel*_*osh 11

Object.keys总是 返回string[],因此您将需要铸造。

更小且更强大的版本将使用Object.fromEntries. 另一个小改进是使用原始密钥的类型,带有T[Key].

const hash = {
  "first": "someString",
  "second": 2,
  "third": 3,
};

type Result<T>= {
  [Key in keyof T]: () => T[Key]
};

const transform = <T extends object>(obj: T): Result<T> => {
  return Object.fromEntries(
    Object.keys(obj).map(
        (key) => [key, () => obj[key as keyof T]]
    )
  ) as Result<T>;
}

const a = transform(hash);

const first = a.first(); // returns "string"
//    ^? const first: string
const second = a.second(); // return "number"
//    ^? const second: number
Run Code Online (Sandbox Code Playgroud)

游乐场链接