leuisken.github.io
leuisken.github.io copied to clipboard
关于ts的一个疑问?
关于ts的一个疑问?
这篇文章本质上是我作为一个
typescript
初学者的请教,希望能有各位更有经验的朋友的指点。
一直以来没有在项目中实践过typescript
,所以今年过年休假的时候,打算尝试一下。
在使用Function.prototype.bind
的时候,注意到了一个让我很诧异的点。VSCode中,对于bind
方法的定义如下:
/* lib.es5.d.ts */
/**
* 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;
我们都知道,bind
这个方法在Javascript中是用来解决函数this作用域的问题的,其返回值类型必然是函数。对于ts来说,我们使用他的一个核心目的就是通过强类型来提供更好的限制和语法补全,可为什么关于bind
的返回值定义却是any
。
在之后的尝试中,我隐隐约约感受到了问题的所在,就是ts对于这种高阶函数
写定义,好像都很难把返回函数的定义清晰表示出来。
为此我请教了@yenshih,他给我看了一下redux/compose的d.ts的实现:https://github.com/reactjs/redux/blob/master/index.d.ts#L416 ,并说了一句“最终还是会落到any的”。
这段代码果然如他所说,在对有限的参数(1, 2, 3, 4)做了类型限制之后,最终落到了any:
/* rest */
export function compose<R>(
f1: (b: any) => R, ...funcs: Function[]
): (...args: any[]) => R;
在后面一些朋友学习交流后,@Chion82也表达了一些他的意见:“函数式和强类型有那么一丁点儿冲突,不是说不能强类型,但是这样静态分析很困难”。
这和我的感觉也是一致的,你总要在高阶函数灵活性和强类型约束之间做一些取舍(any大法好!),至于如何取舍,应该就是取决于开发人员结合项目及自身来决定的了。
我觉得@Chion82说的对
我觉得 @Chion82 说的对
我觉得 @Chion82 说的对
我觉得 @Chion82 说的对
我觉得 @Chion82 说的对
我觉得 @Chion82 说的对
补充 @rabbitmeow 提供的issue作为参考:https://github.com/Microsoft/TypeScript/issues/212
ts3.0有新进展了,支持泛型解构。
https://zhuanlan.zhihu.com/p/38789971
ts 的每一次升级都在解决这些问题呢