【问题标题】:"Type '() => string[]' is missing the following properties from type 'string[]': pop, push, concat, join, and 25 more" error occurs in typescript“类型 '() => string[]' 缺少类型 'string[]' 中的以下属性:pop、push、concat、join 和 25 更多”错误出现在打字稿中
【发布时间】:2020-03-29 21:46:18
【问题描述】:

我想通过获取环境变量的值来设置配置文件。
但我因以下错误而延迟:

类型“() => string[]”缺少类型“string[]”中的以下属性:pop、push、concat、join 等 25 个。

// env set
// MQTT_BROKER_TOPIC=/test/stack/overflow/kbg, /test/stack/overflow/kbg22

// interface
export interface BrokerInfo {
  host: string;
  port: number;
  topic: string[];
};

// topic return data
const envBrokerParse = (): string[] => {
  let result:string[] = [];
  const envBrokerTopic: string|undefined = process.env.MQTT_BROKER_TOPIC;

  if (!envBrokerTopic) { result = envBrokerTopic.split(','); }
  if (result.length === 0) { result = ['/test/stack/overflow/kbg']; }

  return result;
}

/**
 * mqtt broker info
 */
export const mqttBrokerInfo: Array<BrokerInfo> = [
  {
    host: 'localhost',
    port: 1883,
    topic: envBrokerParse, // type error
  },
];

尝试将“envBrokerParse”的返回值放入“主题”中,但发生错误。
我认为“envBrokerParse”必须返回一个 string[] 类型。
但我不知道为什么会出现这个错误。是什么原因?

【问题讨论】:

  • if(!envBrokerTopic) 表示如果未定义,则拆分它。这导致错误无法读取未定义的属性“拆分”。我认为这是阻止它推断所有路径返回字符串 []
  • @ShanonJackson 非常感谢您的回答。正如你所说,我尝试将 if(!envBrokerTopic) 更改为 if (envBrokerTopic === undefined) 但我仍然遇到同样的错误。
  • 对不起,因为您需要 envBrokerParse() 来执行该函数,该函数本身在执行之前不能分配给 string[];误解了错误
  • @ShanonJackson 感谢您编写示例代码。如果将上面编写的 mqttBrokerInfo 变量添加到代码中,您将得到相同的错误。
  • 未读,执行函数错误消失。留下答案

标签: typescript


【解决方案1】:

这就是你想要的

export const mqttBrokerInfo: Array<BrokerInfo> = [
  {
    host: 'localhost',
    port: 1883,
    topic: envBrokerParse(), // no type error  what you want is envBrokerParse()
  },
];

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2021-02-04
    • 2023-02-07
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 2018-03-03
    • 2017-12-22
    • 1970-01-01
    相关资源
    最近更新 更多