简体   繁体   English

为什么将“ any”类型的对象设置为具有特定类型的属性不会引发TS编译错误?

[英]Why setting object of “any” type to property with specific type doesn't throw TS compilation error?

Why this code is not throwing any Typescript errors (see TS playground ): 为什么此代码没有引发任何Typescript错误(请参阅TS操场 ):

interface ErrorData {
    code: number;
    message: string;
}

interface EnrichedError {
    description: string;
    error: ErrorData;
}

const a: any = "bla bla bla";
const b: EnrichedError = {
    description: 'this is a test',
    error: a
}

Why it's possible to set b.error to a? 为什么可以将b.error设置为a?

Because that's the point of any , it is assignable to all types, and all types are assignable to it. 因为这就是any的要点,所以它可以分配给所有类型,并且所有类型都可以分配给它。

It is your escape hatch, it basically tells TypeScript that "this value can go anywhere" 这是您的逃生舱口,它基本上告诉TypeScript“此值可以随处可见”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 TypeScript 会抛出错误:TS2339:“EventTarget”类型上不存在属性“错误” - Why does TypeScript throw the error: TS2339: Property 'error' does not exist on type 'EventTarget' 为什么这种基于联合的类型不抛出错误? - Why doesn't throw an error this union based type? 为什么下面的 TypeScript 程序不会抛出类型错误? - Why doesn't the following TypeScript program throw a type error? TS2339-明显有效的TS文件中的“类型上不存在属性”错误 - TS2339 - 'Property doesn't exist on type' error in an apparently valid TS file 为什么 obj['NonExistentKey'] 不在 TS 中抛出错误? - Why doesn't obj['NonExistentKey'] throw an error in TS? TS 类型防护未检测到非空 class object 属性 - TS Type guard doesn't detect a non-empty class object property TS(2352)声明具有动态属性的对象和一个具有特定类型的属性 - TS(2352) Declare object with dynamic properties and one property with specific type 如何动态说明对象的属性具有特定类型的TS - How to dynamically explain TS that the property of the object has specific type VUE 3 TS 2339:属性 xxx 在类型 { 上不存在 - VUE 3 TS 2339 : The property xxx doesn't exist ont type { TS 属性在泛型定义的类型上不存在 - TS property doesn't exist on type defined by generic
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM