Given the following object, how can I tell if all employees have a non null value for the SSN property?
Employees:
{ id: 0, name: "John", SSN: "1234" }
{ id: 1, name: "Mark", SSN: "1876" }
{ id: 2, name: "Sue", SSN: "98826" }
Assuming that 0 is not a valid SSN, you can use Number(Employees[i].SSN) > 0 to make that determination:
const Employees = [
{ id: 0, name: "A", SSN: "1234" }, // true
{ id: 1, name: "B", SSN: "1876" }, // true
{ id: 2, name: "C", SSN: "" }, // false
{ id: 3, name: "D", SSN: null }, // false
{ id: 4, name: "E", SSN: undefined }, // false
{ id: 5, name: "F" }, // false
{ id: 6, name: "G", SSN: "98826" }, // true
];
function hasSSN <T extends {SSN?: string | null | undefined}>(value: T): value is T & {SSN: string} {
return Number(value.SSN) > 0;
}
for (const employee of Employees) {
console.log(employee.name, hasSSN(employee));
}
Demo:
const Employees = [
{ id: 0, name: "A", SSN: "1234" },
{ id: 1, name: "B", SSN: "1876" },
{ id: 2, name: "C", SSN: "" },
{ id: 3, name: "D", SSN: null },
{ id: 4, name: "E", SSN: undefined },
{ id: 5, name: "F" },
{ id: 6, name: "G", SSN: "98826" }, // true
];
function hasSSN(value) {
return Number(value.SSN) > 0;
}
for (const employee of Employees) {
console.log(employee.name, hasSSN(employee));
}