当您定义像type X = { }
这样的类型时,它将具有隐式索引签名,因此它可以作为具有索引签名的泛型参数传递,而相同的interface
则没有(这实际上是我发现的行为上的唯一差异,正如我继续说的那样……)
type A = {
a: string
}
interface B {
b: string
}
type Constraint<T extends Record<string, unknown>> = true;
type test1 = Constraint<A>
type test2 = Constraint<B> // Error, as expected, since it does not have an index signature
不过,A的隐式索引签名是什么?为什么它的行为与显式索引签名不同?
type A = {
a: string
}
interface C {
[x: string]: string
c: string
}
let a: A = { };
let c: C = { };
a.x = ''; // Error
c.x = ''; // Ok, only an explicitly defined index signature behaves like one
我不明白,如果这个隐式签名的行为不像一个隐式签名,那么它有什么意义?它是否像上面的例子一样实现为传递泛型约束的黑客?在这种情况下,它对类型判断有实际影响吗?