Search code examples
typescriptinterfacemember

What is the need of optional members in typescript interface?


I'm following an online typescript tutorial (not in english, but I'll traslate the example):

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

The explanation of the ? is that it's used to make proprerties optional. The question (that my tutorial doesn't answers) is: if the interface is defined in TS to estabilish a contract to assure that some properties are always present, what is the usefulness to make them optional? Because additional (and then, optional) properties can be handled at object/class definition level instead.

For example, I understand optional methods in Java interfaces, because they have a default method body that can be reused in implementing classes. But there, at first sight, seems a little nonsense.


Solution

  • The optional members define properties that may be present but don't have to be present.

    For example let's consider the following function

    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}
        `)
    }
    

    The following calls are valid:

     // 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: ''}) 
    

    The function can use any field of the interface, but optional fields don't have to be specified on the caller side. Also if we pass an object literal, the compiler can check that only properties of the interface are specified and that required properties are present, while not requiring us to pass optional properties at all.

    It is worth mentioning that interfaces don't have to be implemented by classes, as in the example above, interfaces are used to describe the shapes of objects. These objects may either be classes or object literals, especially when using object literals it is very useful to only have to specify the required fields, and define the optional fields only as needed.