[IMP] hooks: improve useRef typings

With this commit, we can get the type for the target component for a
ref.

By default, if the generic type is not given, the ref will simply use
the base Component type.
This commit is contained in:
Géry Debongnie
2020-04-30 15:58:29 +02:00
committed by aab-odoo
parent 559fadb62a
commit b8d3618afa
2 changed files with 6 additions and 6 deletions
+5 -5
View File
@@ -94,12 +94,12 @@ export const onWillUpdateProps = makeAsyncHook("willUpdatePropsCB");
* The purpose of this hook is to allow components to get a reference to a sub * The purpose of this hook is to allow components to get a reference to a sub
* html node or component. * html node or component.
*/ */
interface Ref { interface Ref<C extends Component = Component> {
el: HTMLElement | null; el: HTMLElement | null;
comp: Component | null; comp: C | null;
} }
export function useRef(name: string): Ref { export function useRef<C extends Component = Component>(name: string): Ref<C> {
const __owl__ = Component.current!.__owl__; const __owl__ = Component.current!.__owl__;
return { return {
get el(): HTMLElement | null { get el(): HTMLElement | null {
@@ -111,9 +111,9 @@ export function useRef(name: string): Ref {
} }
return null; return null;
}, },
get comp(): Component | null { get comp(): C | null {
const val = __owl__.refs && __owl__.refs[name]; const val = __owl__.refs && __owl__.refs[name];
return val instanceof Component ? val : null; return val instanceof Component ? (val as C) : null;
}, },
}; };
} }
+1 -1
View File
@@ -267,7 +267,7 @@ describe("hooks", () => {
class WidgetC extends Component { class WidgetC extends Component {
static template = xml`<div class="outer-div">Hello<WidgetB t-ref="mywidgetb" /></div>`; static template = xml`<div class="outer-div">Hello<WidgetB t-ref="mywidgetb" /></div>`;
static components = { WidgetB }; static components = { WidgetB };
ref = useRef("mywidgetb"); ref = useRef<WidgetB>("mywidgetb");
} }
const widget = new WidgetC(); const widget = new WidgetC();