omi icon indicating copy to clipboard operation
omi copied to clipboard

TS: types for custom event is hard to infer

Open xcatliu opened this issue 6 years ago • 2 comments

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?

xcatliu avatar Oct 23 '18 16:10 xcatliu

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 avatar Oct 24 '18 13:10 volodymyrlut

@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);
  }
}

xcatliu avatar Oct 25 '18 05:10 xcatliu