简体   繁体   中英

Use of interface instead of 'any' type in typescript

在此处输入图像描述 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

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
}

You can use typescript type definition. eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM