代码之家  ›  专栏  ›  技术社区  ›  d-_-b

如何让typescript检查有效的对象属性名称

  •  1
  • d-_-b  · 技术社区  · 5 年前

    我使用的是typescript,有一个用不同人名定义的对象:

    const data = {
       John: someTypedVariable,
       Alex: someTypedVariable,
       Anna: someTypedVariable,
       ... hundreds more added over time
    }
    

    如果我尝试访问 data.missingValue 它将正确地无法编译。

    如果我尝试迭代对象:

    for(const key in data){
       const item = data[key]; // error
    }
    

    Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ John: ....

    我可以改变 data 致:

    const data: Record<string, someTypedVariable> = {
        ...
    }
    

    但这样我就失去了打字功能,这会导致像这样的错误 数据丢失值 .

    那么,有没有一种方法可以在不明确定义密钥列表的情况下保证有效属性,比如:

    type keys = "John" | "Alex" | "Anna" | ...hundreds more
    
    1 回复  |  直到 5 年前
        1
  •  4
  •   CertainPerformance    5 年前

    如果需要使用 for..in ,在定义键之后,断言键是对象的属性:

    for (const key in data) {
        const typedKey = key as keyof typeof data;
        const item = data[typedKey];
    }
    

    (如果不使用 typedKey (再一次)

    另一种方法是使用 Object.entries :

    Object.entries(data).forEach(([key, item]) => {
      // ..
    });
    
    推荐文章