Search code examples
wso2ballerinaballerina-swan-lake

Destructured rest variable contains other fields as `never` type and cannot be used in assignment directly


Check the following ballerina code

type Student record {|
    string name;
    string school;
|};

type HolidayRequest record {|
    record {|
        *Student;
        int noOfDays;
    |} student;
    string teacher;
|};

function testFn(HolidayRequest req) {
    record {|*Student; int noOfDays;|} {noOfDays, ...studentData} = req.student;
    Student student = {...studentData};
    // undefined field 'noOfDays' in record 'Student'
}

The type of studentData is record {|never noOfDays?; string name; string school;|} and we cannot pass this as a rest field for variable typed record {|string name; string school;|};. Why we are not allowing this?

I have tried manually adding the values of the fields separately, but that's not the way I want.

Update:

  • Updated the title of the question

Solution

  • This seems to be a bug when using a record with never-typed optional fields in a spread field.

    A workaround in this scenario would be to use the mapping value via an equivalent static type that does not have never-typed fields.

    Student s1 = studentData;
    Student s2 = {...s1};