functionalComponent.test-d.tsx 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import {
  2. h,
  3. Text,
  4. FunctionalComponent,
  5. expectError,
  6. expectType,
  7. Component
  8. } from './index'
  9. // simple function signature
  10. const Foo = (props: { foo: number }) => h(Text, null, props.foo)
  11. // TSX
  12. expectType<JSX.Element>(<Foo foo={1} />)
  13. expectType<JSX.Element>(<Foo foo={1} key="1" />)
  14. expectType<JSX.Element>(<Foo foo={1} ref="ref" />)
  15. // @ts-expect-error
  16. expectError(<Foo />)
  17. // @ts-expect-error
  18. expectError(<Foo foo="bar" />)
  19. // @ts-expect-error
  20. expectError(<Foo baz="bar" />)
  21. // Explicit signature with props + emits
  22. const Bar: FunctionalComponent<
  23. { foo: number },
  24. { update: (value: number) => void }
  25. > = (props, { emit }) => {
  26. expectType<number>(props.foo)
  27. emit('update', 123)
  28. // @ts-expect-error
  29. expectError(emit('nope'))
  30. // @ts-expect-error
  31. expectError(emit('update'))
  32. // @ts-expect-error
  33. expectError(emit('update', 'nope'))
  34. }
  35. // assigning runtime options
  36. Bar.props = {
  37. foo: Number
  38. }
  39. // @ts-expect-error
  40. expectError((Bar.props = { foo: String }))
  41. Bar.emits = {
  42. update: value => value > 1
  43. }
  44. // @ts-expect-error
  45. expectError((Bar.emits = { baz: () => void 0 }))
  46. // TSX
  47. expectType<JSX.Element>(<Bar foo={1} />)
  48. // @ts-expect-error
  49. expectError(<Foo />)
  50. // @ts-expect-error
  51. expectError(<Bar foo="bar" />)
  52. // @ts-expect-error
  53. expectError(<Foo baz="bar" />)
  54. const Baz: FunctionalComponent<{}, string[]> = (props, { emit }) => {
  55. expectType<{}>(props)
  56. expectType<(event: string) => void>(emit)
  57. }
  58. expectType<Component>(Baz)
  59. const Qux: FunctionalComponent<{}, ['foo', 'bar']> = (props, { emit }) => {
  60. emit('foo')
  61. emit('foo', 1, 2)
  62. emit('bar')
  63. emit('bar', 1, 2)
  64. }
  65. expectType<Component>(Qux)