How to set the current page to a different page in the document?

Creating a plugin and I want to be able to switch between pages to add frames and text to pages that are intentionally left blank. I’m starting with the cover page.

  let coverPage: PageNode = figma.root.findChild(n => n.type === "PAGE" && n.name === "📔 Cover");
figma.currentPage = coverPage;

returns an error of:

Type 'PageNode | null' is not assignable to type 'PageNode'.
  Type 'null' is not assignable to type 'PageNode'.

Can anyone shed some light on what I’m doing wrong?

The error is telling you that the returned value from figma.root.findChild is potentially null, and the value of figma.currentPage should only be of type PageNode and not of type null.

You need to confirm that the page returned by figma.root.findChild is not null. In your situation, this could happen if the name of the page changes from "📔 Cover" to something else, for example.

if (coverPage !== null) {
  figma.currentPage = coverPage;
}

Thank you for your reply. I tried that in the code and it returns the same error:

type or paste code here

let coverPage: PageNode = Figma.root.findChild(n => n.type === “PAGE” && n.name === “:notebook_with_decorative_cover: Cover”);

if (coverPage !== null) {
Figma.currentPage = coverPage;
}

Type 'PageNode | null' is not assignable to type 'PageNode'.
  Type 'null' is not assignable to type 'PageNode'.

I’ve also tried the getNodeByID function since this is for a file init - the number will always be the same. Doesn’t work that way either though.

  let coverPage: PageNode = figma.getNodeById("1:13");

That’s odd. The only other thing I can think of is to use a non-null assertion (exclamation mark at the end of the variable name) to tell TypeScript that you are absolutely certain the value of coverPage is not nullable.

if (coverPage !== null) {
  figma.root.currentPage = coverPage!
}

If this doesn’t work I’m not sure what else to suggest. Best of luck.

At a second glance, I actually think in this case the error has to do with the type you have given coverPage. You need to type it as PageNode | null, as well as confirm that the resulting value is not null prior to setting the current page.

let coverPage: PageNode = ...

should be

let coverPage: PageNode | null = ...