Typescript tip:interface 与 type 区别 interface 没有部署 索引签名

234 阅读1分钟

typescript 中的 typeinterface 的异同想必大多数人都比较清楚(不了解的参考这个),但是有一点相比大多数人不知道,那就是 interface 没有部署索引签名,type 部署有索引签名

interface A {
  a:string
}

type B = Record<string,unknown>

declare let a:A;
declare let b:B

b = a
/* 
   Type 'A' is not assignable to type 'B'.
   Index signature for type 'string' is missing in type 'A'.
*/

如果换用 type 来声明 A

type A = {
  a:string
}

type B = Record<string,unknown>

declare let a:A;
declare let b:B

b = a
// no error

play

具体原因是 interface 有声明合并的行为, typescript 认为它是不安全的

interface C {
  x:string
}
interface C {
  a:number
}
const c:C = {
  x:'1'
}
// Property 'a' is missing in type '{ x: string; }' but required in type 'C'.

参考: github.com/microsoft/T…