传入方法的字符串对象被简化,导致了类型推断的问题。

huangapple go评论56阅读模式
英文:

The string object passed in by the method is simplified, resulting in the problem of type inference

问题

以下是你要的翻译部分:

我想要实现一个用于键名重命名的通用类型。一开始,它正常工作。

但是,当我将它放入方法中时,它可以访问不存在的键。

我发现最初用于 `{ a: 'c' }` 的类型在通用类型中被简化为 `{ a: string }`

这导致方法的返回值变成了 `{[x: string]: 1}`。理想情况下,它应该返回 `{c: 1}`
英文:

The following text in English comes from machine translation.

I want to implement a generic type for key name renaming. At first, it works normally.

type PickRename<T extends {}, F extends {}> = { [K in keyof T & keyof F as F[K] extends string ? F[K] : K]: T[K] }

type A = { a: 1, b: 2 }

type B = { a: 'c' }

type C = PickRename<A, B>

type D = C['c']

type E = C['e'] // TS2339: Property 'e' does not exist on type 'C'.

But when I put it in the method, it can access keys that do not exist.

function pickRename<F extends {}>(p: F): PickRename<A, F> {
  return 0 as unknown as any
}

const b = pickRename({ a: 'c' })

b.e // Under normal circumstances, this line should report an error

I found that the type originally used for the {a:' c '} was simplified to {a: string} in the generic type.

传入方法的字符串对象被简化,导致了类型推断的问题。

This causes the return value of the method to become {[x: string]: 1}. Ideally, it should return {c: 1}.

答案1

得分: 1

你可以在参数上使用 as const

const b = pickRename({ a: 'c' } as const)

或者将变量声明为 as const

const obj = { a: 'c' } as const
const b = pickRename(obj)

对于即将推出的 TypeScript 5.0(目前仍在测试中),有一个新的 const 泛型类型,所以你可以这样声明函数:

function pickRename<const F extends {}>(p: F): PickRename<A, F>
英文:

you can use as const on the parameter:

const b = pickRename({ a: &#39;c&#39; } as const)

or declare the variable as const

const obj = { a: &#39;c&#39; } as const
const b = pickRename(obj)

and for the upcoming typescript 5.0 (still in beta at this moment), there is a new const generic type, so you can delare the function like this:

function pickRename&lt;const F extends {}&gt;(p: F): PickRename&lt;A, F&gt;

huangapple
  • 本文由 发表于 2023年2月26日 21:07:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572191.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定