Как декларировать динамические свойства объектов в TypeScript
Приме из компонента VueJs(Версия: 2, class-style-component):
<v-container>
<v-row
v-for="(item, index) in shortcodes"
:key="index"
>
<v-col>
Замена №{{ index }}([__{{ index }}__])
<edit-select-dropdown-options-single
:ref="`editSelectDropdownOptionsSingle${index}`"
:value="item.options"
@select-option="setAnswer(index, $event)"
@remove-option="removeOption(item.options, $event)"
/>
</v-col>
</v-row>
</v-container>
Формируется динамический ref. Далее мне необходимо обратится к этому ref:
this
.$refs[`editSelectDropdownOptionsSingle${replacement.shortcode_key}`}[0]
.someMethod(someArgs);
Документация по refs.
Как мне описать что по этому ключу есть массив с и у каждого элемента доступен метод someMethod?
Ответы (2 шт):
Автор решения: Александр Рогонов
→ Ссылка
Ну если по-деревенски, то как-то вот так.
interface MySpecialComponent {
someMethod: (payload: string) => void
}
и в коде:
(this.$refs[`editSelectDropdownOptionsSingle${replacement.shortcode_key}`] as MySpecialComponent).someMethod('Два прихлопа три притопа');
Автор решения: Не быть рабом на Руси
→ Ссылка
Добился желаемого результата без глушилок(eslint-disable-next-line,@ts-ignore).
const name = `editSelectDropdownOptionsSingle${replacement.shortcode_key}`;
const refs = this.$refs[name];
if (Array.isArray(refs)) {
const component = refs[0];
if (component instanceof EditSelectDropdownOptionsSingle) {
component.setSelected(shortcodes[replacement.shortcode_key].options[0].id);
}
}
Возможно, я что-то не понимаю, но почему-то TSC не понимает без этих проверок, что $refs может содержать массив и я могу обратится к этому массиву по нулевому индексу и элементом будет экземпляр класса EditSelectDropdownOptionsSingle, который унаследован от Vue и является компонентом.