defineOptions.test-d.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { expectType, defineOptions, Slots, describe } from './index'
  2. describe('no args', () => {
  3. const { props, attrs, emit, slots } = defineOptions()
  4. expectType<{}>(props)
  5. expectType<Record<string, unknown>>(attrs)
  6. expectType<(...args: any[]) => void>(emit)
  7. expectType<Slots>(slots)
  8. // @ts-expect-error
  9. props.foo
  10. // should be able to emit anything
  11. emit('foo')
  12. emit('bar')
  13. })
  14. describe('with type arg', () => {
  15. const { props, attrs, emit, slots } = defineOptions<{
  16. props: {
  17. foo: string
  18. }
  19. emit: (e: 'change') => void
  20. }>()
  21. // explicitly declared type should be refined
  22. expectType<string>(props.foo)
  23. // @ts-expect-error
  24. props.bar
  25. emit('change')
  26. // @ts-expect-error
  27. emit()
  28. // @ts-expect-error
  29. emit('bar')
  30. // non explicitly declared type should fallback to default type
  31. expectType<Record<string, unknown>>(attrs)
  32. expectType<Slots>(slots)
  33. })
  34. // with runtime arg
  35. describe('with runtime arg (array syntax)', () => {
  36. const { props, emit } = defineOptions({
  37. props: ['foo', 'bar'],
  38. emits: ['foo', 'bar']
  39. })
  40. expectType<{
  41. foo?: any
  42. bar?: any
  43. }>(props)
  44. // @ts-expect-error
  45. props.baz
  46. emit('foo')
  47. emit('bar', 123)
  48. // @ts-expect-error
  49. emit('baz')
  50. })
  51. describe('with runtime arg (object syntax)', () => {
  52. const { props, emit } = defineOptions({
  53. props: {
  54. foo: String,
  55. bar: {
  56. type: Number,
  57. default: 1
  58. },
  59. baz: {
  60. type: Array,
  61. required: true
  62. }
  63. },
  64. emits: {
  65. foo: () => {},
  66. bar: null
  67. }
  68. })
  69. expectType<{
  70. foo?: string
  71. bar: number
  72. baz: unknown[]
  73. }>(props)
  74. props.foo && props.foo + 'bar'
  75. props.bar + 1
  76. // @ts-expect-error should be readonly
  77. props.bar++
  78. props.baz.push(1)
  79. emit('foo')
  80. emit('bar')
  81. // @ts-expect-error
  82. emit('baz')
  83. })