Skip to main content
Question

How to Distinguish Local Variable from Direct value and Aliases in Figma API 🤔

  • December 15, 2023
  • 1 reply
  • 485 views

Apirak

I’m working with the Figma API, specifically with variables, and I’ve encountered a bit of a puzzle 🧩

I need to determine whether a variable obtained using

let value = figma.variables.getVariableById(variableId)

Is a direct value or an alias?

Right now, I’m using a workaround to guess this, but I’m wondering if there’s an official way to do it.

Here’s a snippet of my current approach:

  private isVariableAlias(obj: any): obj is VariableAlias {
    return (
      obj &&
      typeof obj === "object" &&
      obj.type === "VARIABLE_ALIAS" &&
      typeof obj.id === "string"
    );
  }

  private resolveVariableName(variableId: string): string {
    const variable = figma.variables.getVariableById(variableId);
    if (!variable) {
      return "can't read variable";
    }

    const valueByMode =
      variable.valuesByMode[Object.keys(variable.valuesByMode)[0]];

    if (this.isVariableAlias(valueByMode)) {
      const underlyingVariableName = this.resolveVariableName(valueByMode.id);
      return `${variable.name} → ${underlyingVariableName}`;
    }

    return variable.name;
  }

Is there a more straightforward or official method to check if a variable is an alias or a direct value? Any insights or suggestions would be greatly appreciated! 🙏

Thank you! 😊

This topic has been closed for replies.

James_Yang
Figmate

Checking the variable’s value for a specific mode like you’re doing is probably the best way.

Keep in mind that a variable can have different values across multiple modes, and some values might be aliases and other values might be primitives. So the code as written, and the idea of “if a variable is an alias” does not account for a collection with more than one mode.


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings