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

interface X {
    a: number
    b: string
}

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

当前回答

索引的差异。

interface MyInterface {
  foobar: string;
}

type MyType = {
  foobar: string;
}

const exampleInterface: MyInterface = { foobar: 'hello world' };
const exampleType: MyType = { foobar: 'hello world' };

let record: Record<string, string> = {};

record = exampleType;      // Compiles
record = exampleInterface; // Index signature is missing

相关问题:类型中缺少索引签名(仅在接口上,而不是在类型别名上)

因此,如果您想为对象编制索引,请考虑这个示例

看看这个问题和这个关于违反利斯科夫原则的问题

评估中的差异

当FirstLevelType为接口时,请查看ExtendeFirst的结果类型

/**
 * When FirstLevelType is interface 
 */

interface FirstLevelType<A, Z> {
    _: "typeCheck";
};

type TestWrapperType<T, U> = FirstLevelType<T, U>;


const a: TestWrapperType<{ cat: string }, { dog: number }> = {
  _: "typeCheck",
};

// {  cat: string; }
type ExtendFirst = typeof a extends FirstLevelType<infer T, infer _>
    ? T
    : "not extended";

当FirstLevelType为类型时,请查看ExtendeFirst的结果类型:


/**
 * When FirstLevelType is type
 */
type FirstLevelType<A, Z>= {
    _: "typeCheck";
};

type TestWrapperType<T, U> = FirstLevelType<T, U>;


const a: TestWrapperType<{ cat: string }, { dog: number }> = {
  _: "typeCheck",
};

// unknown
type ExtendFirst = typeof a extends FirstLevelType<infer T, infer _>
    ? T
    : "not extended";

其他回答

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

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设计模式,或者需要如上所述的合并(除非我有充分的理由,否则我永远不会这么做)。

接口与类型

接口和类型用于描述对象和原语的类型。接口和类型通常可以互换使用,并且通常提供类似的功能。通常由程序员选择自己的偏好。

然而,接口只能描述创建这些对象的对象和类。因此,必须使用类型来描述字符串和数字等原语。

下面是接口和类型之间的两个区别的示例:

// 1. Declaration merging (interface only)

// This is an extern dependency which we import an object of
interface externDependency { x: number, y: number; }
// When we import it, we might want to extend the interface, e.g. z:number
// We can use declaration merging to define the interface multiple times
// The declarations will be merged and become a single interface
interface externDependency { z: number; }
const dependency: externDependency = {x:1, y:2, z:3}

// 2. union types with primitives (type only)

type foo = {x:number}
type bar = { y: number }
type baz = string | boolean;

type foobarbaz = foo | bar | baz; // either foo, bar, or baz type

// instances of type foobarbaz can be objects (foo, bar) or primitives (baz)
const instance1: foobarbaz = {y:1} 
const instance2: foobarbaz = {x:1} 
const instance3: foobarbaz = true 

类型示例:

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

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
    }

2022年更新-

类型别名和接口非常相似,在许多情况下可以自由选择。界面的几乎所有功能在类型中可用,关键区别是类型不能重新打开以添加新的财产,而不是始终可延伸。

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-在类型别名和接口之间

在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”}