简体   繁体   English

如何定义 object 的类型,其属性将从 TypeScript 中的数组中获取

[英]How to define type of an object whose properties are going to be fetched from an array in TypeScript

How to define type of an object whose properties are going to be fetched from an array in TypeScript.如何定义 object 的类型,其属性将从 TypeScript 中的数组中获取。

In the following example, how can I define the type of lookUpMap object?在以下示例中,如何定义lookUpMap object 的类型?

const arr1 = ["a", "b", "c", "d"];
const arr2 = ["x", "y", "b"];

class Arr {
    
    private lookUpMap = {}
    
    constructor(private arr1: string[], private arr2: string[]){}    
    
    linearCompare(){
        for(let i of this.arr1){
            this.lookUpMap[i] = true
        }
        
        for(let i of this.arr2){
            if(this.lookUpMap[i]){
                return console.log(true);
            }
        }
        return console.log(false);
    }
}

const arrComp = new Arr(arr1, arr2);
arrComp.linearCompare()

Thank you谢谢

The most straightforward type I can think of for lookupMap is a dictionary-like object with a string index signature whose properties are of type true | undefined对于lookupMap ,我能想到的最直接的类型是类似于字典的object,其属性类型为true | undefined 字符串索引签名 true | undefined : true | undefined

  private lookUpMap: { [k: string]: true | undefined } = {}

This will let you write true to any string-valued key, as in this.lookUpMap[i] = true , and understand that when you read from a string-valued key, the result will either be true or undefined , as in if (this.lookupMap[i]) {...} .这将允许您将true写入任何字符串值的键,如this.lookUpMap[i] = true ,并了解当您从字符串值的键读取时,结果将为trueundefined ,如if (this.lookupMap[i]) {...}

Note that this has nothing to do with the fact that your keys are coming from arrays;请注意,这与您的密钥来自 arrays 的事实无关; lookupMap will allow you to index into it with any string whatsoever. lookupMap将允许您使用任何string对其进行索引。

Playground link to code Playground 代码链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM