相关疑难解决方法(0)

为什么扩展本机对象是一种不好的做法?

每个JS意见领袖都说扩展原生对象是一种不好的做法.但为什么?我们是否获得了性能?他们是否害怕有人以"错误的方式"做到这一点,并添加了可枚举的类型Object,几乎破坏了任何对象上的所有循环?

TJ Holowaychukshould.js为例.他增加了一个简单的getterObject,一切工作正常(来源).

Object.defineProperty(Object.prototype, 'should', {
  set: function(){},
  get: function(){
    return new Assertion(Object(this).valueOf());
  },
  configurable: true
});
Run Code Online (Sandbox Code Playgroud)

这真的很有道理.例如,可以扩展Array.

Array.defineProperty(Array.prototype, "remove", {
  set: function(){},
  get: function(){
    return removeArrayElement.bind(this);
  }
});
var arr = [0, 1, 2, 3, 4];
arr.remove(3);
Run Code Online (Sandbox Code Playgroud)

是否有任何反对扩展本机类型的论据?

javascript prototype prototypal-inheritance

121
推荐指数
7
解决办法
3万
查看次数

获取数组文字的索引类型

假设我有以下数组文字:

const list = ['foo', 'bar', 'baz'] as const;
Run Code Online (Sandbox Code Playgroud)

我正在尝试生成一个表示该数组的可能索引的类型。我尝试按如下方式实现:

const list = ['foo', 'bar', 'baz'] as const;

type ListIndex = Exclude<keyof (typeof list), keyof []>;
Run Code Online (Sandbox Code Playgroud)

ListIndex现在变成"0" | "1" | "2"0 | 1 | 2

谁能告诉我如何获得所需的0 | 1 | 2类型?

typescript

4
推荐指数
1
解决办法
2645
查看次数

使用打字稿过滤对象键

这是一个显示问题的沙箱。https://codesandbox.io/s/trusting-moon-n058k?file=/src/index.ts

输入

data.types = {
        starter: true,
        main: false,
        side: false,
        dessert: true,
        drink: false
    }
Run Code Online (Sandbox Code Playgroud)

期望的输出

recipe.types = ["starter", "dessert"]
Run Code Online (Sandbox Code Playgroud)

解决方案

type NewRecipeFormValues = {
    types: {
        starter: boolean,
        main: boolean,
        side: boolean,
        dessert: boolean,
        drink: boolean
    }
}

const postNewRecipe = (data: NewRecipeFormValues) => {
  let recipe = JSON.parse(JSON.stringify(data));
  recipe.types = Object.keys(data.types).filter(
    (key: keyof NewRecipeFormValues["types"]) => data.types[key]
  );
};

Run Code Online (Sandbox Code Playgroud)

问题:无论我使用什么类型,Typescript 都不会关闭。

任何帮助将不胜感激,因为我失去了理智

javascript typescript

4
推荐指数
1
解决办法
4546
查看次数

打字稿错误在类型上找不到带有“字符串”类型参数的索引签名

我对 TS 还很陌生......我有这种特殊类型:

export type MyType = {
  high: {
    age: number;
    preview: [{ [key: string]: string | number }];
  };
  low: {
    age: number;
    preview: [{ [key: string]: string | number }];
  };
  medium: {
    age: number;
    preview: [{ [key: string]: string | number }];
  };
};
Run Code Online (Sandbox Code Playgroud)

我通过数据对象键进行映射:

{Object.keys(data)          
         .map((item: string, key: number) => {
            return (
              data &&
              data[item]?.preview && (
                < component here >
              )
            );
          })}
Run Code Online (Sandbox Code Playgroud)

数据类型是正确的,但 TS 抱怨“data[item]?.preview”。

它说:

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“MyType”。在“MyType”类型上找不到带有“string”类型参数的索引签名。

谢谢

javascript typescript

1
推荐指数
1
解决办法
2万
查看次数