简体   繁体   English

typescript可选参数类型检查

[英]typescript optional parameter type check

I've got a function (func) on a class (MyClass) with an optional parameter. 我在类(MyClass)上有一个带有可选参数的函数(func)。 The type of the optional parameter (MyInterface) has only optional properties. 可选参数(MyInterface)的类型只有可选属性。

I expected a compiler error when I call foo with a primitive like a number. 当我用一个像数字的原语来调用foo时,我预计会出现编译器错误。 But thats not the case. 但事实并非如此。 Why is it like that? 为什么会那样? And is there a way to tell the type system to mark that as an error? 有没有办法告诉类型系统将其标记为错误?

interface MyInterface {
    foo?: string
}

class MyClass {
    func(b?: MyInterface) : void {}
}

let c = new MyClass();
c.func();
c.func({ foo: 'bar' });
c.func({ foo: 30 });       // compiler error: OK
c.func({});
c.func(60);                // No compiler error: Not what I expect

The reason this happens is that number is compatible with {} . 发生这种情况的原因是number{}兼容。 (for example, imagine an argument of type {toFixed: (n: number) => string} , that too, is compatible with number ). (例如,想象一下{toFixed: (n: number) => string}类型的参数,它也与number兼容)。

You can also think about it this way: you can do anything with a number, that you could with a {foo?: string} . 您也可以这样思考: 您可以使用{foo?: string}对数字执行任何操作

Let's introduce some dirty console.log-debugging: 我们来介绍一些脏的console.log-debugging:

interface MyInterface {
    foo?: string
}

class MyClass {
    func(b?: MyInterface): void {
        console.log(`b:${b}`);
        if (b != undefined) {
            console.log(`b.foo:${b.foo}`);
        }
    }
}

let c = new MyClass();
c.func();
c.func({ foo: 'bar' });
c.func({ foo: 30 });       // compiler error: OK
c.func({});
c.func(60);                // No compiler error: Not what I expect

Results are: 结果是:

b:undefined

b:[object Object]
b.foo:bar

b:[object Object]
b.foo:30

b:[object Object]
b.foo:undefined

b:60
b.foo:undefined

Let's focus on the last two results. 让我们关注最后两个结果。

MyInterface has only foo parameter, which is moreover optional. MyInterface只有foo参数,而且是可选的。 So actually anything is of type MyInterface . 所以实际上任何东西都是MyInterface类型。 That's why parameter b has value 60. b is in this case of type MyInterface without optional foo member. 这就是为什么参数b值为60. b在这种情况下是MyInterface类型而没有可选的foo成员。

If you remove optional operator from foo member then compiler will throw the exception. 如果从foo成员中删除可选运算符,则编译器将抛出异常。 It will do the same if you add additional, non optional parameter to MyInterface . 如果向MyInterface添加其他非可选参数,它将执行相同的MyInterface

Maybe it seems counter-intuitive but it's not. 也许它似乎违反直觉,但事实并非如此。 In the form you presented, the MyInterface doesn't define anything. 在您提供的表单中, MyInterface没有定义任何内容。 You ask compiler to guard input to have foo parameter... or not have it. 你要求编译器保护输入有foo参数......或者没有它。 So why should it check if input is object ? 那么为什么要检查输入是否是object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM