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 · 9 comments

Comments

Projects
None yet
8 participants
@LeuisKen
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

This comment has been minimized.

Orange-C commented Apr 12, 2018

我觉得@Chion82说的对

@kkmikako

This comment has been minimized.

kkmikako commented Apr 12, 2018

我觉得 @Chion82 说的对

4 similar comments
@rexxara

This comment has been minimized.

rexxara commented Apr 12, 2018

我觉得 @Chion82 说的对

@MaAnShanGuider

This comment has been minimized.

MaAnShanGuider commented Apr 12, 2018

我觉得 @Chion82 说的对

@rabbitooops

This comment has been minimized.

rabbitooops commented Apr 13, 2018

我觉得 @Chion82 说的对

@TenkaiRuri

This comment has been minimized.

TenkaiRuri commented Apr 13, 2018

我觉得 @Chion82 说的对

@LeuisKen

This comment has been minimized.

Owner

LeuisKen commented Apr 16, 2018

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

@AlexStacker

This comment has been minimized.

AlexStacker commented Jul 27, 2018

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

@LeuisKen

This comment has been minimized.

Owner

LeuisKen commented Aug 14, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment