TypeScript Extract to inner function drops narrowed type

pxq42qpu  于 2个月前  发布在  TypeScript
关注(0)|答案(3)|浏览(35)

Bug报告

🔎 搜索词

  • refactor
  • refactoring

🕗 版本与回归信息

4.8.0-dev.20220616,非回归

💻 代码

function doThing(x: number | string) { 
    if (typeof x === 'string') {
        x.charCodeAt(0); // Run extract to inner function here
    }
}

🙁 实际行为

生成的代码无效:

function doThing(x: number | string) {
    if (typeof x === 'string') {
        newFunction();
    }

    function newFunction() {
        x.charCodeAt(0); // Error here: x is of type number | string
    }
}

🙂 预期行为

在这种情况下,我们不应该提供重构功能,或者以某种方式将缩小的类型传递给函数。

pepwfjgg

pepwfjgg1#

我们以某种方式将缩小的类型传递给函数。
相关: #9998

e0bqpujr

e0bqpujr2#

我认为逻辑可能是这样的:对于每个封闭标识符,如果该标识符的缩小类型与其声明类型不同,则应将其提升为内部函数的参数。

function doThing(x: number | string) {
    if (typeof x === 'string') {
        newFunction(x);
    }

    function newFunction(x: string) {
        x.charCodeAt(0); // Error here: x is of type number | string
    }
}

我们可能希望将这里的 x 重命名为其他名称,因为局部词法遮蔽非常糟糕。

tcomlyy6

tcomlyy63#

Another example when you try to extract a method for the code that is in if (isFoo(foo)) { :

interface IFoo {
	id: string;
}

interface IBar {
	id: string;
}

function isFoo(obj: any): obj is IFoo {
	return typeof obj === 'string';
}

function migrate(foo: IBar | IFoo) {
	if (isFoo(foo)) {
		const bar = foo;
		console.log(bar);
	} else {
		console.log(foo);
	}
}

相关问题