如何解决将对象键合并到类中
因此,我有一个外部对象,其属性已分配给该类。我如何使打字稿理解那些键将成为类的键?
const object = {
objectKey: 'whatever'
}
class someClass {
classKey: string
constructor(){
Object.keys(object).forEach(key => this[key] = key)
}
someMethod(){
console.log(this.objectKey) // how do I make it understand it exists?
}
}
解决方法
在希望编译器知道类的实例接口具有更多属性的情况下,可以使用declaration merging。这是我的处理方式:
type MyObject = typeof object; // make a named type with statically known keys
interface SomeClass extends MyObject { } // declare the SomeClass interface as extending it
class SomeClass { ... } // merge the SomeClass class instance interface into it
然后,编译器还将看到object
的键/值也属于SomeClass
实例。请注意,这会绕过--strictPropertyInitialization
保护,并且如果您无法初始化合并的属性也不会警告您。所以要小心做。也许像这样:
class SomeClass {
classKey: string = "initializeMePlease" // compiler will catch if you don't do this
constructor() {
Object.assign(this,object); // compiler will not catch if you don't do this
}
someMethod() {
console.log(this.objectKey); // no error here now
}
}
好的,希望能有所帮助;祝你好运!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。