omi
omi copied to clipboard
TS: types for custom event is hard to infer
Omi use this syntax to create a custom event:
// trigger CustomEvent
this.fire('abc', { name: 'dntzhang', age: 12 })
This is very flexible, but it brings difficulties to type inference.
Specifically, how can parent component know it has a onAbc
props? What is the type of evt.detail
?
You can resolve this issue like you would normally do in, for example, react on typescript - declaring an Interface and relying on it at parent's component.
@volodymyrlut You are right, we can write an interface to describe the onAbc
, then parent component can rely on it.
However, in React, child component can also rely on it:
interface ChildProps {
onAbc: (n: number) => string;
}
class Child extends React.Component<ChildProps> {
doSomething() {
// Here ts know that onAbc should pass an argument with number type
this.props.onAbc(200);
}
}
interface ChildProps {
onAbc: (n: number) => string;
}
class Child extends Omi.WeElement<ChildProps> {
doSomething() {
// It's hard to know that if the first argument is string 'abc', then the second argument needs to be a number
this.fire('abc', 200);
}
}