Home > Software design >  Is it possible to set a union type for ref value in Vue.js with TypeScript?
Is it possible to set a union type for ref value in Vue.js with TypeScript?

Time:06-19

Firstly, I described the type File by manually enumerating its possible values as type literals. Then I specified the type of selectedFile as the union of File and null to set the initial value to null.

type File = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H";
let selectedFile = ref<File | null>(null);
function move() {
    let newPosition = new Position(selectedFile, selectedRank);
    // ...
}

And the error I get:

let selectedFile: Ref<File | null>
Argument of type 'Ref<File | null>' is not assignable to parameter of type
'File'.ts(2345)

CodePudding user response:

A ref was provided where ref value is expected, which is a common mistake with refs that can be detected by TypeScript.

Ref type needs to be narrowed where it's used. For nullable types, it can be either type guard:

if (unref(selectedFile)) {
  let newPosition = new Position(unref(selectedFile), selectedRank);
  ...

Or if ref value is guaranteed to exist at this point and requires no runtime check, it can be non-null assertion:

let newPosition = new Position(unref(selectedFile)!, selectedRank);
  • Related