【发布时间】:2021-03-04 12:23:59
【问题描述】:
我有一个类型列表:
type A = 1
type B = 2
type X = 'x'
type Y = 'y'
我将收到如下对象:Record<string, A | B>。例如:{ test1: A, test2: B, test3: A}。我想创建一个返回这种类型的函数:{ test1: X, test2: Y, test3: X }
我知道我们可以做到:type Result<T> = T extends A ? X: T extends B ? Y : never 映射 A 到 x 和 B 到 Y,但这是我能做的最好的:
function transform <U extends string> (p: Record<U, A | B>): Record<U, Result<A | B>> {
const result = {} as Record<U, Result<A | B>>
(Object.keys(p) as U[]).forEach(k => (result[k] = p[k] === 1 ? 'x' as const : 'y' as const))
return result
}
const a = transform({ test1: 1 as const, test2: 2 })
// a: Record<"test2" | "test1", "x" | "y">
// So a.test1 is of type 'x' | 'y' and not 'x'
当您不知道输入的确切形状时,我实际上不确定我想要实现的目标是否可以使用打字稿......
示例:
| input type | result type |
|---|---|
| { foo: A; bar: B } | { foo: X; bar: Y } |
| { test1: A; test2: B; test3: A } | { test1: X; test2: Y; test3: X } |
| { test1: A; test2: A; test3: A } | { test1: X; test2: X; test3: X } |
| { stuff: A } | { stuff: X } |
基本上,知道A type 将被映射到̀X type, and B typewill be mapped toY type, I want that my transform`函数返回我一个对象,我可以确保:
-
input中不存在的键在output中不存在,因此output[key]应该引发错误 - 如果
input[key]属于A 类型,则output[key]被正确推断为X类型。
这可能吗?
【问题讨论】:
-
您能否提供更多示例,说明您尝试通过一些预期和意外行为实现的目标?
-
好主意。谢谢!
标签: typescript types