gxk28
gxk28

Reputation: 105

How to typecheck angular component template

I have a custom component that takes two inputs. Using TypeScript, I want to enforce that the second input can only be provided if the first input is also provided.

e.g.:

export class MyTestClass implements Test{
  @Input() dog?: string;
  @Input() treat?: string; // Should only be able to exist if dog also exists
}

I have tried creating a generic interface for the component to implement, like so:

interface Test<Dog extends string | undefined = string> {
  dog?: Dog;
  treat?: Dog extends string ? string : undefined
}

But unfortunately, typescript does not complain when I try to use the template the wrong way:

<my-test-class [treat]="'not type-checked'">
</my-test-class>

Is there any way to enforce this relationship between inputs in Angular (hopefully during compile-time and not at run-time)?

Upvotes: 1

Views: 67

Answers (1)

Robin De Schepper
Robin De Schepper

Reputation: 6355

You can use the selector of the @Component decorator:

@Component({
 template: "...",
 style: "...",
 selector: `
  app-my-component[dog],
  app-my-component[dog][treat],
  app-my-component:not([treat])
 `
})
class MyComponent { }

I'm using , for or operations, [attr] to select on the presence of attributes, and the :not pseudo-selector to exclude the case were just treat is present.

Upvotes: 1

Related Questions