In the following code snippets, the object spread syntax should generate a typescript error, but surprisingly no errors are being thrown.
It's important to note that I intentionally added a typo in the address
property for this test.
Snippet A.1. - no error detected
interface TestType {
company?: string;
address?: string;
}
function testFunction(): TestType {
const cond = true;
const testDto = {
...(cond ? { company: '' } : {}),
...(cond ? { addressss: '' } : {}),
};
return testDto;
}
Snippet A.2. - no error detected
interface TestType {
company?: string;
address?: string;
}
function testFunction() {
const cond = true;
const testDto:TestType = {
...(cond ? { company: '' } : {}),
...(cond ? { addressss: '' } : {}),
};
return testDto;
}
Snippet A.3. - no error detected
interface TestType {
company?: string;
address?: string;
}
function testFunction() {
const cond = true;
const testDto= {
...(cond ? { company: '' } : {}),
...(cond ? { addressss: '' } : {}),
};
return testDto as TestType;
}
Snippet B.1. - error successfully caught
This snippet successfully throws a typescript error by removing the object spread syntax and placing the interface definition right after the constant name.
interface TestType {
company?: string;
address?: string;
}
function testFunction() {
const cond = true;
const testDto:TestType = {
company: '',
addressss: '',
};
return testDto;
}
Snippet B.2. - no error detected
Even without the object spread syntax, this snippet does not throw a typescript error, despite defining the interface in the function return type.
interface TestType {
company?: string;
address?: string;
}
function testFunction():TestType {
const cond = true;
const testDto = {
company: '',
addressss: '',
};
return testDto;
}
I verified my code on an online TypeScript editor to rule out any potential environment issues.
If anyone can shed light on what might be causing this anomaly, or provide a solution to detect misspellings when using object spread syntax, it would be greatly appreciated!
Many thanks in advance!