|
| 1 | +import { Ref, ref, isRef, unref, reactive, expectType } from './index'; |
| 2 | + |
| 3 | +function plainType(arg: number | Ref<number>) { |
| 4 | + // ref coercing |
| 5 | + const coerced = ref(arg); |
| 6 | + expectType<Ref<number>>(coerced); |
| 7 | + |
| 8 | + // isRef as type guard |
| 9 | + if (isRef(arg)) { |
| 10 | + expectType<Ref<number>>(arg); |
| 11 | + } |
| 12 | + |
| 13 | + // ref unwrapping |
| 14 | + expectType<number>(unref(arg)); |
| 15 | + |
| 16 | + // ref inner type should be unwrapped |
| 17 | + const nestedRef = ref({ |
| 18 | + foo: ref(1), |
| 19 | + }); |
| 20 | + expectType<Ref<{ foo: number }>>(nestedRef); |
| 21 | + expectType<{ foo: number }>(nestedRef.value); |
| 22 | + |
| 23 | + // ref boolean |
| 24 | + const falseRef = ref(false); |
| 25 | + expectType<Ref<boolean>>(falseRef); |
| 26 | + expectType<boolean>(falseRef.value); |
| 27 | + |
| 28 | + // ref true |
| 29 | + const trueRef = ref<true>(true); |
| 30 | + expectType<Ref<true>>(trueRef); |
| 31 | + expectType<true>(trueRef.value); |
| 32 | + |
| 33 | + // tuple |
| 34 | + expectType<[number, string]>(unref(ref([1, '1']))); |
| 35 | + |
| 36 | + interface IteratorFoo { |
| 37 | + [Symbol.iterator]: any; |
| 38 | + } |
| 39 | + |
| 40 | + // with symbol |
| 41 | + expectType<Ref<IteratorFoo | null | undefined>>(ref<IteratorFoo | null | undefined>()); |
| 42 | +} |
| 43 | + |
| 44 | +plainType(1); |
| 45 | + |
| 46 | +function bailType(arg: HTMLElement | Ref<HTMLElement>) { |
| 47 | + // ref coercing |
| 48 | + const coerced = ref(arg); |
| 49 | + expectType<Ref<HTMLElement>>(coerced); |
| 50 | + |
| 51 | + // isRef as type guard |
| 52 | + if (isRef(arg)) { |
| 53 | + expectType<Ref<HTMLElement>>(arg); |
| 54 | + } |
| 55 | + |
| 56 | + // ref unwrapping |
| 57 | + expectType<HTMLElement>(unref(arg)); |
| 58 | + |
| 59 | + // ref inner type should be unwrapped |
| 60 | + const nestedRef = ref({ foo: ref(document.createElement('DIV')) }); |
| 61 | + |
| 62 | + expectType<Ref<{ foo: HTMLElement }>>(nestedRef); |
| 63 | + expectType<{ foo: HTMLElement }>(nestedRef.value); |
| 64 | +} |
| 65 | +const el = document.createElement('DIV'); |
| 66 | +bailType(el); |
| 67 | + |
| 68 | +function withSymbol() { |
| 69 | + const customSymbol = Symbol(); |
| 70 | + const obj = { |
| 71 | + [Symbol.asyncIterator]: { a: 1 }, |
| 72 | + [Symbol.unscopables]: { b: '1' }, |
| 73 | + [customSymbol]: { c: [1, 2, 3] }, |
| 74 | + }; |
| 75 | + |
| 76 | + const objRef = ref(obj); |
| 77 | + |
| 78 | + expectType<{ a: number }>(objRef.value[Symbol.asyncIterator]); |
| 79 | + expectType<{ b: string }>(objRef.value[Symbol.unscopables]); |
| 80 | + expectType<{ c: Array<number> }>(objRef.value[customSymbol]); |
| 81 | +} |
| 82 | + |
| 83 | +withSymbol(); |
| 84 | + |
| 85 | +const state = reactive({ |
| 86 | + foo: { |
| 87 | + value: 1, |
| 88 | + label: 'bar', |
| 89 | + }, |
| 90 | +}); |
| 91 | + |
| 92 | +expectType<string>(state.foo.label); |
0 commit comments