Typescript:类型为'的变量;在某些情况下进行t型检查

Typescript:类型为'的变量;在某些情况下进行t型检查,typescript,Typescript,我还在学习复杂的打字稿 在试图弄清楚的时候,我遇到了另一种情况,我不明白Typescript是如何解决的 export type GenericType = { [key: string]: { prop1: string, prop2?: string, prop3?: number, } }; const GoodObj: GenericType = { key1: { prop1: "hi", // p

我还在学习复杂的打字稿

在试图弄清楚的时候,我遇到了另一种情况,我不明白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);
在上面的例子中,如果我像对待
BadObj
一样,将无效的道具放入
GoodObj
中,typescript会抱怨。但是,
BadObj
当我将无效的obj分配给
BadObjGen
时,它不会抱怨

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

const type1: number = 1;
const type2: string = type1; // Type 'number' is not assignable to type 'string'
Typescript类型在什么情况下检查对象


Codesandbox-

这是因为接口不限于特定属性:对象必须具有接口中定义的属性,但允许具有更多属性。下面是一个较小的示例:

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

const BadObjGen:GenericType=BadObj
与GenericType的const BadObjGen=BadObj相同基本上是告诉ts强制转换类型,对象可以强制转换为另一个对象,但两种基本类型,数字和字符串是不可转换的。另请参见:|