dan*_*nvk 4 typescript lodash typescript-generics typescript-declarations
在lodash中,该_.invert函数反转对象的键和值:
var object = { 'a': 'x', 'b': 'y', 'c': 'z' };
_.invert(object);
// => { 'x': 'a', 'y': 'b', 'z': 'c' }
Run Code Online (Sandbox Code Playgroud)
lodash类型当前声明为始终返回string?。string映射:
_.invert(object); // type is _.Dictionary<string>
Run Code Online (Sandbox Code Playgroud)
但是有时候,特别是如果您使用const断言,更精确的类型将是合适的:
const o = {
a: 'x',
b: 'y',
} as const; // type is { readonly a: "x"; readonly b: "y"; }
_.invert(o); // type is _.Dictionary<string>
// but would ideally be { readonly x: "a", readonly y: "b" }
Run Code Online (Sandbox Code Playgroud)
是否有可能得到如此精确的打字?该声明接近:
declare function invert<
K extends string | number | symbol,
V extends string | number | symbol,
>(obj: Record<K, V>): {[k in V]: K};
invert(o); // type is { x: "a" | "b"; y: "a" | "b"; }
Run Code Online (Sandbox Code Playgroud)
键是正确的,但是值是输入键的并集,即,您将丢失映射的特异性。有可能做到这一点吗?
您可以使用保留正确值的更复杂的映射类型来执行此操作:
const o = {
a: 'x',
b: 'y',
} as const;
type AllValues<T extends Record<PropertyKey, PropertyKey>> = {
[P in keyof T]: { key: P, value: T[P] }
}[keyof T]
type InvertResult<T extends Record<PropertyKey, PropertyKey>> = {
[P in AllValues<T>['value']]: Extract<AllValues<T>, { value: P }>['key']
}
declare function invert<
T extends Record<PropertyKey, PropertyKey>
>(obj: T): InvertResult<T>;
let s = invert(o); // type is { x: "a"; y: "b"; }
Run Code Online (Sandbox Code Playgroud)
AllValues首先创建一个包含所有工会key,value对(所以你的例子,这将是{ key: "a"; value: "x"; } | { key: "b"; value: "y"; })。然后,在映射类型中,我们映射value联合中的所有类型,并使用value提取每种类型的原始类型。只要没有重复的值,这就会很好地工作(如果存在重复的值,我们将在出现值的地方获得键的并集)keyExtract
Titian Cernicova-Dragomir 的解决方案真的很酷。今天我找到了另一种用条件类型交换对象键和值的替代方法:
type KeyFromValue<V, T extends Record<PropertyKey, PropertyKey>> = {
[K in keyof T]: V extends T[K] ? K : never
}[keyof T];
type Invert<T extends Record<PropertyKey, PropertyKey>> = {
[V in T[keyof T]]: KeyFromValue<V, T>
};
Run Code Online (Sandbox Code Playgroud)
测试const o:
const o = {
a: "x",
b: "y"
} as const;
// type Invert_o = {x: "a"; y: "b";}
type Invert_o = Invert<typeof o>;
// works
const t: Invert<typeof o> = { x: "a", y: "b" };
// Error: Type '"a1"' is not assignable to type '"a"'.
const t1: Invert<typeof o> = { x: "a1", y: "b" };
Run Code Online (Sandbox Code Playgroud)
invert以与上述答案相同的方式使用 Return type声明函数Invert<T>。
由于 TypeScript 4.1 支持映射类型中的键重映射,这变得相当简单:
const o = {
a: 'x',
b: 'y',
} as const;
declare function invert<
T extends Record<PropertyKey, PropertyKey>
>(obj: T): {
[K in keyof T as T[K]]: K
};
let s = invert(o); // type is { readonly x: "a"; readonly y: "b"; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
273 次 |
| 最近记录: |