【发布时间】:2021-04-20 11:12:16
【问题描述】:
这段代码:
let arrowFn = () => {};
arrowFn.prototype.blah;
在编译时抛出一个错误,因为箭头函数没有 prototypes 但 typescript 没有错误并愉快地转换代码。
为什么?
【问题讨论】:
标签: typescript
这段代码:
let arrowFn = () => {};
arrowFn.prototype.blah;
在编译时抛出一个错误,因为箭头函数没有 prototypes 但 typescript 没有错误并愉快地转换代码。
为什么?
【问题讨论】:
标签: typescript
这里你已经内置了 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
【讨论】: