functionalComponent.test-d.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { h, Text, FunctionalComponent, Component, VNode } from 'vue'
  2. import { expectType } from './utils'
  3. // simple function signature
  4. const Foo = (props: { foo: number }) => h(Text, null, props.foo)
  5. // TSX
  6. expectType<JSX.Element>(<Foo foo={1} />)
  7. expectType<JSX.Element>(<Foo foo={1} key="1" />)
  8. expectType<JSX.Element>(<Foo foo={1} ref="ref" />)
  9. // @ts-expect-error
  10. ;<Foo />
  11. // @ts-expect-error
  12. ;<Foo foo="bar" />
  13. // @ts-expect-error
  14. ;<Foo baz="bar" />
  15. // Explicit signature with props + emits
  16. const Bar: FunctionalComponent<
  17. { foo: number },
  18. { update: (value: number) => void }
  19. > = (props, { emit }) => {
  20. expectType<number>(props.foo)
  21. emit('update', 123)
  22. // @ts-expect-error
  23. emit('nope')
  24. // @ts-expect-error
  25. emit('update')
  26. // @ts-expect-error
  27. emit('update', 'nope')
  28. }
  29. // assigning runtime options
  30. Bar.props = {
  31. foo: Number
  32. }
  33. // @ts-expect-error
  34. Bar.props = { foo: String }
  35. Bar.emits = {
  36. update: value => value > 1
  37. }
  38. // @ts-expect-error
  39. Bar.emits = { baz: () => void 0 }
  40. // TSX
  41. expectType<JSX.Element>(<Bar foo={1} onUpdate={() => {}} />)
  42. // @ts-expect-error
  43. ;<Foo />
  44. // @ts-expect-error
  45. ;<Bar foo="bar" />
  46. // @ts-expect-error
  47. ;<Foo baz="bar" />
  48. const Baz: FunctionalComponent<{}, string[]> = (props, { emit }) => {
  49. expectType<{}>(props)
  50. expectType<(event: string) => void>(emit)
  51. }
  52. expectType<Component>(Baz)
  53. const Qux: FunctionalComponent<{}, ['foo', 'bar']> = (props, { emit }) => {
  54. emit('foo')
  55. emit('foo', 1, 2)
  56. emit('bar')
  57. emit('bar', 1, 2)
  58. }
  59. expectType<Component>(Qux)
  60. const Quux: FunctionalComponent<
  61. {},
  62. {},
  63. {
  64. default: { foo: number }
  65. optional?: { foo: number }
  66. }
  67. > = (props, { emit, slots }) => {
  68. expectType<{
  69. default: (scope: { foo: number }) => VNode[]
  70. optional?: (scope: { foo: number }) => VNode[]
  71. }>(slots)
  72. slots.default({ foo: 123 })
  73. // @ts-expect-error
  74. slots.default({ foo: 'fesf' })
  75. slots.optional?.({ foo: 123 })
  76. // @ts-expect-error
  77. slots.optional?.({ foo: 'fesf' })
  78. // @ts-expect-error
  79. slots.optional({ foo: 123 })
  80. }
  81. expectType<Component>(Quux)
  82. ;<Quux />