【问题标题】:Typescript: variable of type doesn't type check under certain circumstances打字稿:类型变量在某些情况下不进行类型检查
【发布时间】:2020-09-01 06:20:31
【问题描述】:

我仍在学习打字稿的复杂性。

在试图弄清楚 Typescript: Generic to specific type 时,我遇到了另一种情况,我不明白 Typescript 是如何解决的。

export type GenericType = {
    [key: string]: {
      prop1: string,
      prop2?: string,
      prop3?: number,
  }
};
const GoodObj: GenericType = {
  key1: {
    prop1: "hi",
    // prop5: "what", // Type '{ prop1: string; prop5: string; }' is not assignable to type '{ prop1: string; prop2?: string; prop3?: number; }'.
  },
  key2: {
    prop1: "bye",
    prop2: "sup",
  },
};

console.log(GoodObj);

const BadObj = {
  key1: {
    prop1: "hi",
    prop5: "what",
  },
  key2: {
    prop1: "bye",
    prop2: "sup",
  },
};

const BadObjGen: GenericType = BadObj;

console.log(BadObjGen);

在上面的示例中,如果我将无效的道具放入 GoodObj,打字稿会报错,就像我对 BadObj 所做的那样。但是,当我将无效的 obj 分配给 BadObjGen 时,BadObj 不会抱怨。

然而,如果我对原语做同样的事情,它确实会抱怨。

const type1: number = 1;
const type2: string = type1; // Type 'number' is not assignable to type 'string'

Typescript 在什么情况下对对象进行类型检查?

代码沙盒 - https://codesandbox.io/s/typescript-experiment-hp92o?file=/src/index.ts:175-316

【问题讨论】:

标签: typescript


【解决方案1】:

这是因为接口不限于特定的属性:一个对象必须具有接口中定义的属性,但可以有更多。一个较小的例子来证明你是:

interface a {
    x: number;
}

const l = {
    x: 1,
    y: 2
}

const test: a = l; //valid as l has a x: number property, although it also has y: number

//Note: this will throw an error in TS, even though it exists, because you typed it as having only a x-property
test.y = 5; //error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 2021-04-09
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    相关资源
    最近更新 更多