英文:
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: 'c' } as const)
or declare the variable as const
const obj = { a: 'c' } 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<const F extends {}>(p: F): PickRename<A, F>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论