Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于ts的一个疑问? #4

Open
LeuisKen opened this issue Apr 12, 2018 · 10 comments
Open

关于ts的一个疑问? #4

LeuisKen opened this issue Apr 12, 2018 · 10 comments

Comments

@LeuisKen
Copy link
Owner

LeuisKen commented Apr 12, 2018

关于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大法好!),至于如何取舍,应该就是取决于开发人员结合项目及自身来决定的了。

@Orange-C
Copy link

我觉得@Chion82说的对

@kkmikako
Copy link

我觉得 @Chion82 说的对

4 similar comments
@rexxara
Copy link

rexxara commented Apr 12, 2018

我觉得 @Chion82 说的对

@MaAnShanGuider
Copy link

我觉得 @Chion82 说的对

@Coooooooola
Copy link

我觉得 @Chion82 说的对

@rurico
Copy link

rurico commented Apr 13, 2018

我觉得 @Chion82 说的对

@LeuisKen
Copy link
Owner Author

补充 @rabbitmeow 提供的issue作为参考:microsoft/TypeScript#212

@AlexStacker
Copy link

ts3.0有新进展了,支持泛型解构。

@LeuisKen
Copy link
Owner Author

https://zhuanlan.zhihu.com/p/38789971

@LeuisKen
Copy link
Owner Author

LeuisKen commented Dec 6, 2018

image
ts 的每一次升级都在解决这些问题呢

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants