相关疑难解决方法(0)

是否可以在TypeScript中精确键入_.invert?

在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)

typescript lodash typescript-generics typescript-declarations

4
推荐指数
3
解决办法
273
查看次数