If you create an interface with a field named
length of type
number, then arrays (
any[],
string[], etc.) do not implement it, even though they have that field. (Strings, Typed Arrays, and plain objects with the field do work properly, though.)
function isEmpty(list: { length: number; })
{
return list.length === 0;
}
console.log(isEmpty("")); // true
console.log(isEmpty("foo")); // false
console.log(isEmpty({ length: 0 })); // true
console.log(isEmpty({ length: 4 })); // false
console.log(isEmpty(new Uint8Array(0))); // true
console.log(isEmpty(new Uint8Array(3))); // false
console.log(isEmpty([])); // Should be true, but there's a compiler error.
console.log(isEmpty([0, 1, 2])); // Should be false, but there's a compiler error.
(This was tested in the online TypeScript Playground.)