TS2531:.match()期间对象可能为“ null”

时间:2019-12-07 18:08:16

标签: typescript

在下面的代码中,我在fileNameMatches [0]上出现标题错误。它不会在{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} import GHC.TypeLits data Z (n :: Nat) = El Integer instance (KnownNat n) => Show (Z n) where show el@(El e) = show e ++ " (mod " ++ show (natVal el) ++ ")" instance (KnownNat k) => Num (Z k) where (+) el@(El a) (El b) = El (mod (a + b) k) where k = natVal el (-) el@(El a) (El b) = El (mod (a - b) k) where k = natVal el (*) el@(El a) (El b) = El (mod (a * b) k) where k = natVal el negate el@(El a) = El (mod (0 - a) k) where k = natVal el abs el@(El a) = El a where k = natVal el signum el@(El a) = El 1 fromInteger i = El (fromIntegral i) 检查中掉毛。删除该支票不会修复或更改任何内容。有人知道如何解决这个问题吗?

> :set -XDataKinds
> (El 2 :: Z 5) + (El 3 :: Z 5)
0 (mod 5)
> (El 2 :: Z 5) + (El 3 :: Z 7)

<interactive>:15:18: error:
    • Couldn't match type ‘7’ with ‘5’
      Expected type: Z 5
        Actual type: Z 7
    • In the second argument of ‘(+)’, namely ‘(El 3 :: Z 7)’
      In the expression: (El 2 :: Z 5) + (El 3 :: Z 7)
      In an equation for ‘it’: it = (El 2 :: Z 5) + (El 3 :: Z 7)

也尝试过

Boolean()

此测试还返回“可能为空”错误。

1 个答案:

答案 0 :(得分:1)

使用修复!运算符来断言不为空:

 protected getLocalFilename(): string {
    const fileNameMatches: string[]|null = this.filePath.match(/\/(.+\.js)$`/);
    if (Boolean(fileNameMatches)) { 
      return fileNameMatches![0];
    }
    else {
      throw Error("No filename found during regex matching")
    }
  }