如何使TypeScript抱怨其他类型的字符串连接? [英] How to make TypeScript complain about string concatenation with other type?

查看:44
本文介绍了如何使TypeScript抱怨其他类型的字符串连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么即使在严格模式下,TypeScript也不会抱怨

Why even in strict mode TypeScript is not complaining about this

function test(firstName: string, lastName?: string): string {
    return firstName + " " + lastName;
}

test('John');

与此无关

const str: string = '';
const num: object = {};

const result: string = str + num;

我不记得要在屏幕上打印"约翰未定义"或" [对象对象] "的情况.是类型检查的全部要点都应该捕获此类错误吗?(流程做到了)

I don't remember cases when I would want to get and print on the screen 'John undefined' or '[object Object]'. Is the whole point of type checking is supposed to be catching such errors? (Flow does it)

推荐答案

+运算符的上下文中,您不能这样做,因为它旨在支持混合类型,例如在表达式"Count:" + a.length()中.

In the context of the + operator, you can't, because it's designed to be able to support mixed types, for example in the expression "Count: " + a.length().

可以隐式(以+串联)将对象转换为字符串并进行控制.在现代JavaScript中,这可能会证明如下:

The conversion of objects to strings can be implied (in + concatenation) and controlled. In modern JavaScript this might be demonstrated as follows:

let o = {};
o.toString = ()=> "two"
alert("one" + " " + o); // Displays "one two"

因此,实际上没有理由仅根据类型拒绝第二个示例.

So there isn't really a reason to reject the second example just based on types.

对于第一个示例,在抽象的ToString()操作中隐含并定义了从 unknown null 到字符串的转换,尽管我不确定它是否可以更改,似乎定义得很好.现在,它已经定义好了当然可能是使用 tslint 之类的工具进行标记的原因,但是它在ECMAScript中仍然是有效的操作.

As to the first example, conversion from unknown and null to string are implied and defined in abstract ToString() operation, though I'm not sure it's changeable, it seems well defined. Now, it certainly might be reason to flag with a tool like tslint, but it remains a valid operation in ECMAScript.

这篇关于如何使TypeScript抱怨其他类型的字符串连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆