【问题标题】:typescript doesn't error on using arrow function `prototype`打字稿在使用箭头函数“原型”时不会出错
【发布时间】:2021-04-20 11:12:16
【问题描述】:

这段代码:

let arrowFn = () => {};
arrowFn.prototype.blah;

在编译时抛出一个错误,因为箭头函数没有 prototypes 但 typescript 没有错误并愉快地转换代码。

为什么?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    这里你已经内置了 FUnction 类型:

    interface Function {
        /**
         * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function.
         * @param thisArg The object to be used as the this object.
         * @param argArray A set of arguments to be passed to the function.
         */
        apply(this: Function, thisArg: any, argArray?: any): any;
    
        /**
         * Calls a method of an object, substituting another object for the current object.
         * @param thisArg The object to be used as the current object.
         * @param argArray A list of arguments to be passed to the method.
         */
        call(this: Function, thisArg: any, ...argArray: any[]): any;
    
        /**
         * For a given function, creates a bound function that has the same body as the original function.
         * The this object of the bound function is associated with the specified object, and has the specified initial parameters.
         * @param thisArg An object to which the this keyword can refer inside the new function.
         * @param argArray A list of arguments to be passed to the new function.
         */
        bind(this: Function, thisArg: any, ...argArray: any[]): any;
    
        /** Returns a string representation of a function. */
        toString(): string;
    
        prototype: any;
        readonly length: number;
    
        // Non-standard extensions
        arguments: any;
        caller: Function;
    }
    

    如您所见,FUnction.prototype 具有 any 类型。这就是为什么你没有任何错误。

    let arrowFn = () => {};
    
    function x(){}
    
    
    x.prototype
    arrowFn.prototype
    

    x 和 arrowFn 都指向同一个 Function.prototype 类型。

    如果您将箭头函数替换为function allowFn(){},您将只收到undefined,不会出错

    更新

    const x = () => { }
    const y = function () { }
    function z() { }
    
    type X = typeof x // () => void
    type Y = typeof y // () => void
    type Z = typeof z // () => void
    
    

    【讨论】:

    • 所以,虽然箭头函数是在五年前加入到JS中的,但是TS并没有给它们一个合适的定义,而是把它们当作标准函数对待??
    • @marzelin 我做了更新,但似乎是的。也许 smbd 会纠正我
    猜你喜欢
    • 1970-01-01
    • 2017-01-04
    • 2016-08-26
    • 2018-09-30
    • 2015-12-12
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 2022-07-27
    相关资源
    最近更新 更多