繁体   English   中英

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

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

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

在以下示例中,如何定义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()

谢谢

对于lookupMap ,我能想到的最直接的类型是类似于字典的object,其属性类型为true | undefined 字符串索引签名 true | undefined

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

这将允许您将true写入任何字符串值的键,如this.lookUpMap[i] = true ,并了解当您从字符串值的键读取时,结果将为trueundefined ,如if (this.lookupMap[i]) {...}

请注意,这与您的密钥来自 arrays 的事实无关; lookupMap将允许您使用任何string对其进行索引。

Playground 代码链接

暂无
暂无

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

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