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

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

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! :pray:

Thank you! :blush:

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.

1 Like