functionalComponent.test-d.tsx 1.6 KB

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