打字稿对象类型不会显示省略分号的错误

I found a strange thing with object type declaration. I expect the p2 is the correct one, but it worked with a , or even I omit the semi-colon, it's still fine. Why is it so inconsistent?

let p: {
    x: number,
    y: string
} = {
    x: 1,
    y: "abc",
}


let p2: {
    x: number;
    y: string
} = {
    x: 1,
    y: "abc",
}


let p3: {
    x: number
    y: string
} = {
    x: 1,
 ...

Playground Link

评论
April
April

由于自动分号插入(ASI),JavaScript中的分号是可选的。 TypeScript也遵循ASI。 ASI并不简单,在某些情况下,省略分号会导致意外的运行时错误。但是TypeScript的类型系统进一步消除了JavaScript中的一些极端情况。

// valid
class Employee{
  name: string;
  age: number;
}

// also valid
class Employee{
  name: string
  age: number
}

Here is a link of a similar question that might help you-- Are semicolons necessary in typescript?

点赞
评论