"$node" can vary a bit by context, but here are some ways to set $node:
$routeName = \Drupal::routeMatch()->getRouteName(); $node = NULL; // $variables['node']. if (isset($variables['node'])) { $node = $variables['node']; if (is_numeric($variables['node'])) { $node = \Drupal::entityTypeManager()->getStorage('node')->load($variables['node']); } } // $variables['row']. if (isset($variables['row']) && !empty($variables['row']->nid)) { $node = \Drupal::entityTypeManager()->getStorage('node')->load($variables['row']->nid); } // $routeName === 'entity.node.canonical'. if ($routeName === 'entity.node.canonical') { $node = \Drupal::routeMatch()->getParameter('node'); } // $routeName === 'entity.node.revision'. if ($routeName === 'entity.node.revision') { $revisionId = \Drupal::routeMatch()->getParameter('node_revision')->getRevisionId(); $node = node_revision_load($revisionId); } // $routeName === 'entity.node.preview'. if ($routeName === 'entity.node.preview') { $node = \Drupal::routeMatch()->getParameter('node_preview'); } if ($node) { // run your code... }
Specifically, it looks like you're after:
// Get route name. $routeName = \Drupal::routeMatch()->getRouteName(); // Check if route is node revision. if ($routeName === 'entity.node.revision') { $revisionId = \Drupal::routeMatch()->getParameter('node_revision')->getRevisionId(); $node = node_revision_load($revisionId); }
This will fully load your node object and ->getType() should work without error.