Reputation:
is it a good idea to use interface instead of using any as a variable type. say i have 3 functions where i am defining variables which can be of alphanumeric format. Hence instead of defining it as of any can i do as an interface
Upvotes: 0
Views: 1657
Reputation: 13539
Yes it is the right way. The goal of TS is to provide types instead of any
values from javascript.
The goal is to have all variables typed, if you don't know its type - try to use generic
or unknown
instead of any
. A type def is more extensible than an interface def. An interface works for objects and classes, a type works for everything including primitives, unions and infers, but a class can implement interfaces only, not types.
If you need to assert type you can use type guards:
const isNumber = (value: unknown): value is number {
return typeof value === 'number';
}
const something: any = 123;
something += 1; // valid
something.callFake(); // valid
if (isNumber(something)) {
something += 1; // valid
something.callFake(); // invalid
}
In your case use can use generics.
public addRow(row: Row): boolean {
let constraints: unknown = getConstraints(this.config); // unknown fits too
let table: any = localStorage.getItem(row.tableName);
let rowData = {};
}
public getData<T>( // <- T, when we don't know type.
table_name: string, entity_name?: string,
entity_value?: T
): boolean {
let tableRecord: object[] = [];
let allTableData: Array<object> = JSON.parse(
localStorage.getItem(table_name) || ""
).data;
}
public deleteRecord<T extends string>( // <- T, when we don't know type.
table_name: string,
entity_name: string,
entity_value: T
): boolean {
return !!entity_value; // works
}
public updateRecord<T, D extends object>( // <- T, D, when we don't know type.
table_name: string,
entity_name: string,
entity_value: T,
updation_data: D
): boolean {
if (typeof entity_name === 'string) {
// now we know it's a string.
}
return !entity_value || !updation_data; // works
}
Upvotes: 1
Reputation: 336
You can use typescript type
definition. e.g. if u have multiple types for a variable, you can create a single type as:
type Foo = Bar1 | Bar2 | Bar3
where Bar1
, Bar2
, Bar3
can be different interfaces or even types.
Upvotes: 0