0

我是键入脚本的新手。我正在编写一个函数来格式化字符串。

type patamTypes = string | number | number[];

function myFunc(sTemplate: string, params: patamTypes): string {
   
     if (typeof params == 'string'){
         params = [params]; //getting the error here
     }

}

我收到这个错误。Type 'string' is not assignable to type 'number'.

4

1 回答 1

2

patamTypes可以是字符串或数字或数字数组。在类型检查params是一个字符串之后,您试图将其变异为与您在其中定义的内容不兼容的字符串数组patamType- 您的类型唯一可接受的数组是数字数组。

如果您希望将字符串转换为数字,请在将其params转换为数组之前执行此操作。

于 2020-10-17T22:45:20.043 回答