functionalComponent.test-d.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import {
  2. type Component,
  3. type FunctionalComponent,
  4. Text,
  5. type VNode,
  6. h,
  7. } from 'vue'
  8. import { expectType } from './utils'
  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. ;<Foo />
  17. // @ts-expect-error
  18. ;<Foo foo="bar" />
  19. // @ts-expect-error
  20. ;<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. emit('nope')
  30. // @ts-expect-error
  31. emit('update')
  32. // @ts-expect-error
  33. emit('update', 'nope')
  34. }
  35. // assigning runtime options
  36. Bar.props = {
  37. foo: Number,
  38. }
  39. // @ts-expect-error
  40. Bar.props = { foo: String }
  41. Bar.emits = {
  42. update: value => value > 1,
  43. }
  44. // @ts-expect-error
  45. Bar.emits = { baz: () => void 0 }
  46. // TSX
  47. expectType<JSX.Element>(<Bar foo={1} onUpdate={() => {}} />)
  48. // @ts-expect-error
  49. ;<Foo />
  50. // @ts-expect-error
  51. ;<Bar foo="bar" />
  52. // @ts-expect-error
  53. ;<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)
  66. const Quux: FunctionalComponent<
  67. {},
  68. {},
  69. {
  70. default: { foo: number }
  71. optional?: { foo: number }
  72. }
  73. > = (props, { emit, slots }) => {
  74. expectType<{
  75. default: (scope: { foo: number }) => VNode[]
  76. optional?: (scope: { foo: number }) => VNode[]
  77. }>(slots)
  78. slots.default({ foo: 123 })
  79. // @ts-expect-error
  80. slots.default({ foo: 'fesf' })
  81. slots.optional?.({ foo: 123 })
  82. // @ts-expect-error
  83. slots.optional?.({ foo: 'fesf' })
  84. // @ts-expect-error
  85. slots.optional({ foo: 123 })
  86. }
  87. expectType<Component>(Quux)
  88. ;<Quux />