在打字稿中不能将“字符串”类型分配给“数字”类型

时间:2020-10-17 22:35:24

标签: typescript

我是初次输入脚本。我正在写一个格式化字符串的函数。

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'.

1 个答案:

答案 0 :(得分:2)

您的s = "hello" print(s) for i, l in enumerate(s): print(s[:-(i + 1)]) print(s) while len(s) > 0: s = s[:-1] print(s) ''' hello hell hel he h hello hell hel he h ''' 可以是字符串,数字或数字数组。在检查类型patamTypes是否为字符串之后,您正尝试将其更改为与params中定义的字符串数组不兼容的字符串数组-类型唯一可接受的数组是数字。

如果您希望将字符串转换为数字,请先执行此操作,然后再将patamType更改为数组。