6

Variable starts off with an empty ref, for example it might be one of these:

const myString = ref();
const myString = ref('');
const myString = ref<string>();
const myString = ref<string | null>();
const myString = ref<string | null>(null);
const myString = ref<string | undefined>();
const myString = ref<string | undefined>(undefined);
const myString = ref<string | null | undefined>();

Then later it's given a value:

myString.value = "I am a string";

The ref is then assigned an empty value again, for example it might be one of these:

myString.value = '';
myString.value = null;
myString.value = undefined;

Which combination of these is best to use in Vue 3?

Or maybe you do something else?

When used in the wild I'm looking for maximum compatibility with Vue 3, TypeScript type safety, and no Eslint errors.

TinyTiger
  • 1,801
  • 7
  • 47
  • 92
  • 1
    It doesn't really have anything to do with Vue3 _per se_: it's up to how you handle data in your app. It boils down to conventions and preferences, especially when it comes to deciding between `null` and `undefined`: https://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript. Personally, I would use `const myString = ref()`, unless you want to explicitly use an empty string. It also depends if you enable strict null checks in TypeScript. – Terry Feb 12 '22 at 23:40
  • 1
    It could depend on the context, but I generally use `string | null` (initialized to `null`), because I feel like it's the most explicit. Choosing `undefined` over `null` would work just as well, it's mostly just a matter of preference. – Loris Wit Feb 12 '22 at 23:45

1 Answers1

6

As the documentation shows, no ref argument results in inferred union type and requires less code to achieve the result:

// inferred type: Ref<number | undefined>
const n = ref<number>()

The difference between undefined and null in this case is mostly semantic. It may be beneficial to use ref<string | null>(null) if it's necessary to determine whether a value is intentionally or accidentally empty, this may be beneficial for debugging purposes. Also they behave differently in JSON, if a value is supposed to be serialized, null is a preferable choice.

ref('') can be used if it doesn't matter whether a value is initialized or just empty, and there are string method calls that require to take care of optional chaining for null or undefined values, e.g. myString.value?.toLowerCase().

Estus Flask
  • 206,104
  • 70
  • 425
  • 565