Home > OS >  How do I determine whether type T is extending an interface?
How do I determine whether type T is extending an interface?

Time:11-05

I want to create a default value for a type that extends from Entity, or let the value be null otherwise. This is my (pseudo)code:

export interface Entity {
    id: number;
    // ...
}

@Component({})
export class EpicComponent<T> {
  @Input() data: T[] | null = null;
  @Input() identifier: keyof T | null = T is of type Entity ? 'id' : null; // <--
}

When T is an Entity, I'm sure it has an id, so I want the identifier to be the id by default. However, for some other types I might need another property as identifier. Is this possible in TypeScript? Or perhaps by doing this in a different way? Help is appreciated.

CodePudding user response:

You cannot use the interface to check inheritance, since interfaces are not compiled to JS. But you can use type guards to safely check duck typing like isEntity function is doing.

Does something like this works for you?

export interface Entity {
  id: number;
  // ...
}

function isEntity(o: any): o is Entity {
  return (o as Entity)?.id != null;
}

@Component({})
export class EpicComponent<T> {
@Input() data: T[] | null = null;
@Input() identifier: keyof T | null = null;

ngOnInit() {
  if(isEntity(this.data?.[0])) {
    this.identifier = 'id' as keyof T;
  }
}
}
  • Related