TypeScript中的这些语句(接口与类型)有什么区别?

interface X {
    a: number
    b: string
}

type X = {
    a: number
    b: string
};

当前回答

在typescript中,建议使用“interface”而不是“type”。

“type”用于创建类型别名。您不能使用“接口”执行此操作。type Data=字符串然后,您可以使用“数据”代替字符串const name:string=“Yilmaz”const name:Data=“Yilmaz”

别名非常有用,尤其是在处理泛型类型时。

声明合并:可以合并接口,但不能合并类型。界面人员{name:字符串;}界面人员{年龄:数字;}//我们必须提供两个人的财产常量名称:人={名称:“Yilmaz”,年龄:30岁};函数式编程用户使用“类型”,面向对象编程用户选择“接口”您不能在接口上计算或计算财产,而是在类型中。type Fullname=“name”|“lastname”类型人员={[key in Keys]:字符串}常量名称:人={名字:“Yilmaz”,姓氏:“Bingol”}

其他回答

还有一个不同之处。我会的。。。如果你能解释这种情况的原因,请给你买一杯啤酒:

enum Foo { a = 'a', b = 'b' }

type TFoo = {
  [k in Foo]: boolean;
}

const foo1: TFoo = { a: true, b: false} // good
// const foo2: TFoo = { a: true }       // bad: missing b
// const foo3: TFoo = { a: true, b: 0}  // bad: b is not a boolean

// So type does roughly what I'd expect and want

interface IFoo {
//  [k in Foo]: boolean;
/*
  Uncommenting the above line gives the following errors:
  A computed property name in an interface must refer to an expression whose type is a      
    literal type or a 'unique symbol' type.
  A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
  Cannot find name 'k'.
*/
}

// ???

这种情况让我很想说接口的问题,除非我有意实现一些OOP设计模式,或者需要如上所述的合并(除非我有充分的理由,否则我永远不会这么做)。

类型示例:

//为对象创建树结构。由于缺少交集(&),您无法对接口执行相同的操作

type Tree<T> = T & { parent: Tree<T> };

//键入以限制变量仅分配几个值。接口没有联合(|)

type Choise = "A" | "B" | "C";

//由于类型,您可以通过条件机制声明NonNullable类型。

type NonNullable<T> = T extends null | undefined ? never : T;

界面示例:

//您可以使用OOP接口,并使用“implements”定义对象/类骨架

interface IUser {
    user: string;
    password: string;
    login: (user: string, password: string) => boolean;
}

class User implements IUser {
    user = "user1"
    password = "password1"

    login(user: string, password: string) {
        return (user == user && password == password)
    }
}

//可以使用其他接口扩展接口

    interface IMyObject {
        label: string,
    }

    interface IMyObjectWithSize extends IMyObject{
        size?: number
    }

TypeScript手册给出了答案:

界面的几乎所有功能都是可用的类型。关键区别在于不能重新打开类型以添加新的财产vs始终可扩展的接口。

想加上我的2美分;

我曾经是“界面爱好者”(除了联合、交叉等以外,我更喜欢界面而不是类型)。。。直到我开始使用类型“any key value object”,即Record<string,unknown>

如果键入“任意键值对象”:

function foo(data: Record<string, unknown>): void {
  for (const [key, value] of Object.entries(data)) {
    // whatever
  }
}

如果你使用接口,你可能会走到死胡同

interface IGoo {
  iam: string;
}

function getGoo(): IGoo {
  return { iam: 'an interface' };
}

const goo = getGoo(); 

foo(goo); // ERROR
// Argument of type 'IGoo' is not assignable to parameter of type 
// 'Record<string, unknown>'.
//  Index signature for type 'string' is missing in type 
// 'IGoo'.ts(2345)

虽然打字就像一个符咒:

type Hoo = {
  iam: string;
};

function getHoo(): Hoo {
  return { iam: 'a type' }; 
}

const hoo = getHoo(); 

foo(hoo); // works

这个特定的用例——IMO——产生了不同。

“typescriptlang”似乎建议尽可能使用接口而不是类型。接口与类型别名