我对使用常量值的索引签名和类型扩充有疑问。
以下是我想要使用的代码片段。有人能指出我正确的方向吗?
class Component {
greet() {
console.log( 'hello' );
}
}
const PROPERTY = 'foobar';
interface Element {
// I want here to augment Element
[param: typeof PROPERTY_COMPONENT_INSTANCE]: Component | undefined
}
// ... somewhere else ...
const el = document.getElementById( '#myasd' );
// To be able to get a "Component|undefined" here
const comp = el[PROPERTY];
if( comp ) {
comp.greet();
}
答案 0 :(得分:0)
如果您确定知道,您将获得Component类型的对象, 您可以按如下方式定义类型
const comp = el[PROPERTY] as Component | undefined