为什么TypeScript仅在使用大括号定义时才允许对象上有多余的属性?

为什么TypeScript仅在使用大括号定义时才允许对象上有多余的属性?,typescript,Typescript,定义接口时,TypeScript文档提到,只要对象具有接口的形状,就允许任何多余的对象属性 一个例子 interface Person { name: string } function print(somebody: Person) { console.log(somebody.name); } let obj = { name: "Johnny", additionalProps: true } print(obj); // this is okay 但这是否只适用于

定义接口时,TypeScript文档提到,只要对象具有接口的形状,就允许任何多余的对象属性

一个例子

interface Person {
    name: string
}

function print(somebody: Person) {
    console.log(somebody.name);
}

let obj = { name: "Johnny", additionalProps: true }

print(obj); // this is okay
但这是否只适用于函数参数?下面,我尝试创建一个对象强制转换为特定类型,添加其他属性仅在不使用大括号时才会引发错误

interface Animal {
    name: string;
}

let myDog = <Animal> { 
    name: "Spot",
    altProperty: "anything" // no error
};

myDog.altProperty = "anything else"; // Property 'altProperty' does not exist on type 'Animal'
interface Person {
    name: string
}
interface PersonPlusMore {
    name: string,
    age: number
}

function print(somebody: Person) {
    console.log(somebody.name);
}

let obj : PersonPlusMore = { name: "Johnny", age: 30 }; // <-- notice that we used explicit typing

print(obj); // this is still okay because it has "at least" the properties that your print function requires
界面动物{ 名称:字符串; } 让我的狗={ 名称:“点”, altProperty:“任何内容”//无错误 }; myDog.altProperty=“其他任何内容”//类型“Animal”上不存在属性“altProperty”
在断言对象的类型时,似乎可以为其分配任意多的属性,但不能访问其中任何属性,因为它们不在类型定义中。这是为什么?

typescript中的接口仅提供编译时检查,解释对象上可用的成员

您的代码在这里:

let myDog = <Animal> 
试图将无效对象强制转换为
Animal

现在,您不需要将对象强制转换为
Animal
,就可以这样使用它。你可以写:

interface Animal {
    name: string;
}

let myDog = { 
    name: "Spot",
    altProperty: "anything"
};

myDog.altProperty = "anything else";

doSomething(myDog);
function doSomething(object: Animal) {}

它会很好的工作。事实上,像您这样显式地键入变量的唯一原因是故意捕捉您正在经历的错误。

原因是TypeScript的类型系统基于结构子类型,我认为可以最好地概括为,如果对象具有某个类型的属性,则该对象对应于该类型。有些人开玩笑说,这只是“鸭子打字”(也就是说,如果它像鸭子一样呱呱叫,那么它就是鸭子)

因此,在您的示例中,它实际上与使用接口声明与使用大括号声明无关

interface Animal {
    name: string;
}

let myDog = <Animal> { 
    name: "Spot",
    altProperty: "anything" // no error
};

myDog.altProperty = "anything else"; // Property 'altProperty' does not exist on type 'Animal'
interface Person {
    name: string
}
interface PersonPlusMore {
    name: string,
    age: number
}

function print(somebody: Person) {
    console.log(somebody.name);
}

let obj : PersonPlusMore = { name: "Johnny", age: 30 }; // <-- notice that we used explicit typing

print(obj); // this is still okay because it has "at least" the properties that your print function requires
接口人{
名称:string
}
接口人员plusMore{
名称:string,
年龄:数目
}
函数打印(某人:人){
console.log(someone.name);
}
让obj:PersonPlusMore={姓名:“约翰尼”,年龄:30}//