首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeScript:函数` `includes`‘必须采用相同的类型参数

TypeScript:函数` `includes`‘必须采用相同的类型参数
EN

Stack Overflow用户
提问于 2021-04-21 07:01:10
回答 2查看 85关注 0票数 1

TypeScript中,函数Array.Prototype.includes要求我传递与原始数组相同的类型。但是我在想,使用includes来找出一个任意string类型的键是否存在于一个已知类型的数组中,这不是整个意义所在吗?

请考虑以下代码:

代码语言:javascript
复制
type CONFIG_MODEL = {
  URL: string;
  Protocol: string;
  Port: number;
  Encrypted: boolean;
}

const ALLOWED_KEYS: (keyof CONFIG_MODEL)[] = ['URL', 'Protocol'];

function setup(configs: { [key: string]: string }) {
  Object.keys(configs).forEach(configKey => {
    if (ALLOWED_KEYS.includes(configKey)) {
      // do something
    }
  })
}

TypeScript游乐场

TypeScript在使用includes时抛出一个错误,声明:

“string”类型的参数不能分配给“CONFIG_MODEL的键”类型的参数

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2021-04-21 07:03:55

只需尝试迭代允许的键,而不是整个对象键示例:

代码语言:javascript
复制
type CONFIG_MODEL = {
  URL: string;
  Protocol: string;
  Port: number;
  Encrypted: boolean;
}

type AllowedKeys = Array<keyof CONFIG_MODEL>;

const ALLOWED_KEYS: AllowedKeys = ['URL', 'Protocol'];

const hasProperty=<Obj,Prop extends string>(obj:Obj,prop:Prop):obj is Obj & Record<Prop,string>=>
  Object.prototype.hasOwnProperty.call(obj,prop);

function setup(configs: { [key: string]: string }) {  
  ALLOWED_KEYS.forEach(elem=>{
    if(hasProperty(configs, elem)){
      // do smth with config
      const result = configs[elem] // ok
    }
  })
}
票数 1
EN

Stack Overflow用户

发布于 2022-11-10 16:24:23

这里倒数第二个行中的as string[]强制转换(就在.includes之前)也解决了这个问题:

代码语言:javascript
复制
//type externally defined in original
type ClassicalElement = 'earth' | 'water' | 'wind' | 'fire'; 
const classicalElements = ['earth', 'water', 'wind', 'fire'] as ClassicalElement[];
const isClassicalElement = function(
    possibleElement: string
): possibleElement is ClassicalElement {
    return (classicalElements as string[]).includes(possibleElement);
}

操场链接:使用不带错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67190764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档