【问题标题】:Argument of type 'unknown' is not assignable to parameter of type 'string'“未知”类型的参数不能分配给“字符串”类型的参数
【发布时间】:2019-11-01 14:27:00
【问题描述】:

这是我的代码

index.ts

import { isCTStr } from "./CT/isOCT";

let Avgo: string = "kamo";
let Pult: unknown = 15;
const x = (a: string) => {};

(function() {
  if (!isCTStr(Pult)) {
    return;
  }
x(Pult) // Argument of type 'unknown' is not assignable to parameter of type 'string'.
})();

./CT/isOCT

const isCTStr = (value: unknown): boolean =>
  typeof value === "string" ? true : false;

export {isCTStr}

当我运行文件 index.ts 时出现错误。

“未知”类型的参数不能分配给“字符串”类型的参数。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您需要使用特殊的返回类型来使 isCTStr 成为custom type guard

    const isCTStr = (value: unknown): value is string =>
      typeof value === "string" ? true : false;
    

    PS,三元也是没必要的;您可以通过以下方式获得相同的效果:

    const isCTStr = (value: unknown): value is string =>
      typeof value === "string";
    

    【讨论】:

    猜你喜欢
    • 2021-11-02
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2021-10-13
    • 2019-10-22
    • 2018-06-24
    相关资源
    最近更新 更多