setupHelpers.test-d.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import {
  2. expectType,
  3. defineProps,
  4. defineEmits,
  5. useAttrs,
  6. useSlots,
  7. withDefaults,
  8. Slots,
  9. describe
  10. } from './index'
  11. describe('defineProps w/ type declaration', () => {
  12. // type declaration
  13. const props = defineProps<{
  14. foo: string
  15. }>()
  16. // explicitly declared type should be refined
  17. expectType<string>(props.foo)
  18. // @ts-expect-error
  19. props.bar
  20. })
  21. describe('defineProps w/ type declaration + withDefaults', () => {
  22. const res = withDefaults(
  23. defineProps<{
  24. number?: number
  25. arr?: string[]
  26. obj?: { x: number }
  27. fn?: (e: string) => void
  28. x?: string
  29. }>(),
  30. {
  31. number: 123,
  32. arr: () => [],
  33. obj: () => ({ x: 123 }),
  34. fn: () => {}
  35. }
  36. )
  37. res.number + 1
  38. res.arr.push('hi')
  39. res.obj.x
  40. res.fn('hi')
  41. // @ts-expect-error
  42. res.x.slice()
  43. })
  44. describe('defineProps w/ runtime declaration', () => {
  45. // runtime declaration
  46. const props = defineProps({
  47. foo: String,
  48. bar: {
  49. type: Number,
  50. default: 1
  51. },
  52. baz: {
  53. type: Array,
  54. required: true
  55. }
  56. })
  57. expectType<{
  58. foo?: string
  59. bar: number
  60. baz: unknown[]
  61. }>(props)
  62. props.foo && props.foo + 'bar'
  63. props.bar + 1
  64. // @ts-expect-error should be readonly
  65. props.bar++
  66. props.baz.push(1)
  67. const props2 = defineProps(['foo', 'bar'])
  68. props2.foo + props2.bar
  69. // @ts-expect-error
  70. props2.baz
  71. })
  72. describe('defineEmits w/ type declaration', () => {
  73. const emit = defineEmits<(e: 'change') => void>()
  74. emit('change')
  75. // @ts-expect-error
  76. emit()
  77. // @ts-expect-error
  78. emit('bar')
  79. type Emits = { (e: 'foo' | 'bar'): void; (e: 'baz', id: number): void }
  80. const emit2 = defineEmits<Emits>()
  81. emit2('foo')
  82. emit2('bar')
  83. emit2('baz', 123)
  84. // @ts-expect-error
  85. emit2('baz')
  86. })
  87. describe('defineEmits w/ runtime declaration', () => {
  88. const emit = defineEmits({
  89. foo: () => {},
  90. bar: null
  91. })
  92. emit('foo')
  93. emit('bar', 123)
  94. // @ts-expect-error
  95. emit('baz')
  96. const emit2 = defineEmits(['foo', 'bar'])
  97. emit2('foo')
  98. emit2('bar', 123)
  99. // @ts-expect-error
  100. emit2('baz')
  101. })
  102. describe('useAttrs', () => {
  103. const attrs = useAttrs()
  104. expectType<Record<string, unknown>>(attrs)
  105. })
  106. describe('useSlots', () => {
  107. const slots = useSlots()
  108. expectType<Slots>(slots)
  109. })