打字稿接口中可选成员的需求是什么?

What is the need of optional members in typescript interface?

我正在学习在线打字稿教程(不是英文,但我会翻译示例):

interface Message { 
    email: string; 
    receiver?: string; 
    subject?: string; 
    content: string; 
}

?的解释是,它用来使属性可选。 问题(我的教程没有回答)是:如果在 TS 中定义接口以建立 contract 以确保某些属性始终存在,那么制作它们有什么用处可选?因为可以在 object/class 定义级别处理其他(然后是可选的)属性。

例如,我理解 Java 接口中的可选方法,因为它们有一个默认方法体,可以在实现 类 时重复使用。但是那里,乍一看,似乎有点废话。

可选成员定义可能存在但不必存在的属性。

例如让我们考虑下面的函数

function send(msg: Message): void {
    // Check if the missing properties are present, and provide defaults as needed
    if(!msg.subject) msg.subject= 'no subject';
    if(!msg.receiver) msg.subject= 'no subject';

    console.log(`Subject: ${msg.subject}
    To: ${msg.receiver}
    From: ${msg.email}
    Content: ${msg.content}
    `)
}

以下调用有效:

 // We have the required properties, the contract is satisfied 
send({ email: '', content: ''})

// We have the required properties, the contract is satisfied
send({ email: '', content: '', receiver:'' }) 

 //Invalid missing required proeprty
send({ email: '' }) 

// Invalid, we have excess properties, (only applies to object literals assigned directly to the parameter)
send({ email: '', content: '', Receiver: ''}) 

该函数可以使用接口的任何字段,但不必在调用方指定可选字段。此外,如果我们传递一个对象文字,编译器可以检查是否只指定了接口的属性以及是否存在必需的属性,而根本不需要我们传递可选属性。

值得一提的是,接口不一定非得类实现,如上例中,接口是用来描述对象的形状。这些对象可以是 类 也可以是对象字面量,尤其是在使用对象字面量时,只需指定必填字段并仅根据需要定义可选字段非常有用。