简体   繁体   English

在 typescript 中使用接口而不是“任何”类型

[英]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.使用 interface 而不是使用 any 作为变量类型是个好主意。 say i have 3 functions where i am defining variables which can be of alphanumeric format.假设我有 3 个函数,我在其中定义可以是字母数字格式的变量。 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. TS 的目标是提供类型而不是 javascript 中的any值。

The goal is to have all variables typed, if you don't know its type - try to use generic or unknown instead of any .目标是输入所有变量,如果您不知道它的类型 - 尝试使用genericunknown而不是any A type def is more extensible than an interface def.类型 def 比接口 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.接口适用于对象和类,类型适用于包括原语、联合和推断在内的所有内容,但 class 只能实现接口,不能实现类型。

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.在您的情况下,可以使用 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.您可以使用 typescript type定义。 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.其中Bar1Bar2Bar3可以是不同的接口甚至类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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