I started to write in Typescript. Should I declare my class properties as from type of interface or of a a specific class (that implements that specific interface)?
import { ITable, Table } from "aws-cdk-lib/aws-dynamodb";
import { Construct } from "constructs";
export class Database extends Construct {
public readonly usersTable: Table; // <======== should it be Table(class) or ITable(interface)
constructor(scope, id) {
super(scope, id);
this.usersTable = this.createUsersTable();
}
private createUsersTable(): Table { // <======== should it be Table(class) or ITable(interface)
// some implementation
...
return usersTable;
}
}
What is the better practice?
CodePudding user response:
the Interfaces in CDK are for type checking and for Construct building.
When declaring the object, you have to ask yourself - Is this going to HAVE to be a Table or can it be a Table Like Object? At this point in time there is only one Table like Resource - a Table.
There are some things that have multiple Resources that are some what interchangeable - types of IAM Policies for instance. But even so, the code in the CDK that accepts a policy already accepts an interface.
Unless you are building your own custom Construct objects, then I would stay away from using the Interfaces. It causes confusion, and in Typescript may not even work properly in some cases I believe (not 100% certain, Typescript is not my strength)
Its best to use Interfaces when designing properties/parameters that take a particular type but can take any version of that type. For just straight up object declaration, the Type is better as its always better to be exact and specific than general.
CodePudding user response:
It is always better to use interfaces. However some functions are not available using interfaces in CDK. I use interfaces on constructs input and public methods. For private properties / methods I use interface by default and I change it rarely to concrete type if needed.