详细差异:在打字稿type`和类型断言`表达式作为type`
即使在类型断言basarat解释在他的大书TypeScript Deep Dive:详细差异:在打字稿type`和类型断言`表达式作为type`
基本上,从类型的断言
S到T成功如果任S是T或T亚型是S子类型。
我想知道是什么类型的注释variable: type和类型断言expression as type之间准确的区别,更确切地说,当类型断言是否工作,特别是关于该打字稿错误是一段令人吃惊:看到他们为foo3和foo5变量波纹管:
interface Foo { n?: number;
s: string;
}
const foo1 = {} as Foo; // ok
const foo2 = { n: 1 } as Foo; // ok
const foo3 = { n: '' } as Foo; // KO: "Property 's' is missing..."
const foo4 = { n: '' as any } as Foo; // ok
const foo5 = { n: 1, x: 2 } as Foo; // KO: "Property 's' is missing..."
const foo6 = { s: '', x: 2 } as Foo; // ok
const foo7 = { s: 1, x: 2 } as Foo; // KO: "Types of property 's' are incompatible."
其他差异我注意到:在VSCode的Foo接口重命名n财产被断言不会传播到表情,而它的工作与类型进行批注变量。
回答:
我想知道是什么
variable: type和类型断言表达式类型类型注释之间准确的区别
类型声明variable: type告诉变量必须始终符合声明类型的编译器。它用于通过typechecker时的值分配给变量(该值必须与声明的类型兼容),并且还每当使用变量(变量声明的类型必须与任何方式的变量在使用兼容每个特定的地方)。
类型断言覆盖内置类型兼容性规则。它可以让你告诉编译器,你知道这个值实际上符合你在断言中给出的类型,从而抑制了关于类型不兼容的错误信息。有限制,但是 - 你不能只是断言,变量有你想要的任何类型的(顺便说一句有any类型只是为)。当你在问题中引用,类型断言工作,
从类型S与T断言成功如果任S是T的子类型或T是S
的亚型
它的工作原理正好以这种方式在各实施例:
const foo3 = { n: '' } as Foo; // KO: "Property 's' is missing..." 这里两种类型:{n?: number, s: string}和{n: string}被检查兼容性 - 如果它们中的任何可以被转换成另一种。它不能做任何一种方式:在一个方式,{n: string}缺少非可选s和n有错误的类型(必须为number | undefined);以另一种方式,{n?: number, s: string}有错误类型n(必须是string)。
完整的错误消息是
Type '{ n: string; }' cannot be converted to type 'Foo'. Property 's' is missing in type '{ n: string; }'.
在报告结构类型不兼容,编译器只选择一个不兼容的特性错误消息显示 - 它可以是任何上述三个不兼容的。
const foo4 = { n: '' as any } as Foo; // ok 作品,因为{n?: number, s: string}与{n: any}兼容:第一个可以被分配给第二 - any与任何兼容,s只是忽略(基本上,一个值与类型,如果兼容它拥有所有非可选特性与声明的类型兼容)
const foo5 = { n: 1, x: 2 } as Foo; // KO: "Property 's' is missing..." {n: number, x: number}是不能分配给{n?: number, s: string} - s丢失,因为编译器说:
Type '{ n: number; x: number; }' cannot be converted to type 'Foo'. Property 's' is missing in type '{ n: number; x: number; }'.
const foo6 = { s: '', x: 2 } as Foo; // ok 工作,因为{s: string, x: number}是分配给{n?: number, s: string}:s是确定的,缺少n是可以的,因为它被声明为可选,额外x被忽略
const foo7 = { s: 1, x: 2 } as Foo; // KO: "Types of property 's' are incompatible." 类型的s是不兼容的:
Type '{ s: number; x: number; }' cannot be converted to type 'Foo'. Types of property 's' are incompatible.
Type 'number' is not comparable to type 'string'.
以上是 详细差异:在打字稿type`和类型断言`表达式作为type` 的全部内容, 来源链接: utcz.com/qa/266123.html

