TypeScript 从用法推断JSDoc快速修复破坏了返回函数模式

t0ybt7op  于 6个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(62)

TypeScript版本: 4.0.0-dev.20200712和3.9.6
Visual Studio Code版本: 1.47.0
搜索关键词:https://github.com/microsoft/TypeScript/issues?q=is%3Aissue+is%3Aopen+"Quick+fix"+"return+function "

当在vscode中点击"Quick Fix..."为reduceUntil中的匿名函数时,会导致行为中断,并且reduceUntil返回undefined
你可以在repl.it上玩这个代码

代码

/**
* @param {{(): boolean; (arg0: any): any}} predicate
*/
function reduceUntil (predicate) {
    let stop = false
    return function(accu, x) {
        if (accu.length === 0) stop = false // reset if new accu
        if (predicate(x)) stop = true // stop when true
        if (stop) return accu // return the accumulated
        return accu + x	// append next value to accu
    }
}

预期行为:

/**
* @param {{ (): boolean; (arg0: any): any; }} predicate
*/
function reduceUntil (predicate) {
	let stop = false
	return /** @type {(accu: string, x: string) => string} */ function (accu, x) {
		if (accu.length === 0) stop = false // reset if new accu
		if (predicate(x)) stop = true // stop when true
		if (stop) return accu // return the accumulated
		return accu + x	// append next value to accu
	}
}

实际行为:

/**
* @param {{ (): boolean; (arg0: any): any; }} predicate
*/
function reduceUntil (predicate) {
	let stop = false
	return /**
* @param {string | any[]} accu
* @param {any} x
*/
function (accu, x) {
			if (accu.length === 0) stop = false // reset if new accu
			if (predicate(x)) stop = true // stop when true
			if (stop) return accu // return the accumulated
			return accu + x	// append next value to accu
		}
}
  • 上面的重构是错误的,现在reduceUntil将返回undefined。*
    Playground链接:

另一个被接受的文档重构是将类型定义移动到外部函数的@return部分,如下所示:
https://www.staging-typescript.org/play?useJavaScript=true#code/PQKhCgAIUgBAHAhgJ0QW0gb0wCgJQBckARgPakA2ApogHYDckOKA5gAxF0Cehk3Avv0jxkVACYBLAMaIALlSgxYo2QFdktAM5ZmUqaqKbZyCbRYAaSAA9Dx0yzyQAvAD5IRk2aGixqqVWRFYHAAM1VaKVkJUlpIHz8qAFVaKIocEXFpOSpHTChIAupZd1lSeGdIEMQKTQUCgpV1WLCIqJjdfUsrXPz6+okQpkQ9VQA6ajNZAAtnJydINkcjMoqqmqpIYGA4qlrigchaKgB3PhHevsgD9J8s+RxupdLy+eNVDa2SleOpqli3uqXArXZbwRyNDRnfSbbYQ-6-KGqNCqCjZMQXPpwxGQADU1gAkJ9EPB4H8xIcqFZigA3arvSClREXfjgfhAA

相关问题:

microsoft/vscode#102399
#31836

bnlyeluc

bnlyeluc1#

这对于函数表达式来说似乎是合理的,只要它们不会立即在变量初始化器或类似的地方被赋值。

6vl6ewon

6vl6ewon2#

只要它们没有立即分配给变量初始化器
@DanielRosenwasser 你的意思是下面的代码不正确吗?

/** @type {{(arg0:string):boolean}} */
const equalDash = x => x === '-'
const untilDash = reduceUntil(equalDash) // <- immediately assigned to a variable

我还想指定,我不希望TypeScript编译器推断出返回类型是{(accu: string, x: string) => string}。可能它会是@returns {(accu: string|any[], x: any) => any}

相关问题