TypeScript 忽略 __proto__

txu3uszq  于 2个月前  发布在  TypeScript
关注(0)|答案(4)|浏览(37)

TypeScript版本:2.2.0
代码:

{ __proto__: {} } as { [key: string]: string }

预期行为:
Ok

实际行为:
Type '{ __proto__: {}; }' cannot be converted to type '{ [key: string]: string; }'.

cyvaqqii

cyvaqqii1#

这非常令人烦恼。考虑这个

export const stepComponent = {
    bindings: {
        hasNextStep: '>',
        hasPreviousStep: '>',
        onNextStep: '&',
        onPreviousStep: '&'
    },
    controller: class StepController {
        public hasNextStep: boolean;
        public hasPreviousStep: boolean;
        public onNextStep: Function;
        public onPreviousStep: Function;
    }
};

angular.component('credentialsStep', {
    __proto__: stepComponent,
    bindings: {
        __proto__: stepComponent.bindings,
        user: '>'
    },
    controller: class CredentialsStepController extends stepComponent.controller {

        public credentialsForm: angular.IFormController;
        public user: any;
        public repeatedPassword: string;
    }
});

凭据组件应该是有效的,并且具有步骤组件的所有属性,而它却失败了

[ts]
Argument of type '{ __proto__: { bindings: { hasNextStep: string; hasPreviousStep: string; onNextStep: string; onPr...' is not assignable to parameter of type 'IComponentOptions'.
  Object literal may only specify known properties, and '__proto__' does not exist in type 'IComponentOptions'.
toiithl6

toiithl62#

今晚在为Node创建自定义错误子类时遇到了这个问题。我原以为TypeScript会忽略与.__proto__相关的内容,或者至少有一个机制可以避免它。

class CustomError extends Error {
	constructor (message?: string) {
		// 'Error' breaks prototype chain here
		super(message);

		// restore prototype chain
		const actualProto = new.target.prototype;

		if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; }
	}
}

感谢:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
https://stackoverflow.com/a/48342359

8ljdwjyq

8ljdwjyq3#

在这里也是一样的。我刚刚遇到了这个问题,使用了以下循环结构:
for (let i in qList) { qList[i].prop1.trim(); qList[i].prop2.trim(); }
这是一个简单的对象数组。循环的任务是遍历所有对象并修剪其两个字符串属性。TypeScript的文档提到了遍历数组的索引。问题在于,在完成这个操作后,i的值从索引变为了'contains',这是__proto__
上的一个方法。当我们将TypeScript升级到2.9.2时,这完全破坏了我们的应用程序。在1.8上它运行得很好。

q5iwbnjs

q5iwbnjs4#

请注意,这个RFC中描述了这个问题的完整解决方案:#38385

相关问题