Structural Typing in Object Literals
• Also known as "static typing" or "nominal typing."
• It's based on the structure or shape of the object or class.
• Two types are considered compatible if their structures are equivalent.
• The type system cares about the actual structure and properties of the object, rather than its name or declared type.
interface Pet {
name: string;
}
let pet: Pet;
// dog's inferred type is { name: string; owner: string; }
let dog = { name: "Lassie", owner: "Rudd Weatherwax" };
pet = dog;
console.log(pet.name );
//example 2
function logName(something: { name: string }) {
console.log(something.name);
}
var person = { name: 'matt', job: 'being awesome' };
var animal = { name: 'cow', diet: 'vegan, but has milk of own species' };
var random = { note: `I don't have a name property` };
logName(person); // okay
logName(animal); // okay
logName(random); //error
//example 3
interface Dog {
name:string
}
interface Cat {
name:string
}
interface Person {
firstName:string,
lastName:string
}
let dog:Dog = { name:"mars"}
let cat:Cat = { name:"venus"}
dog=cat; //ok
cat=dog; //ok
let person:Person ={firstName:"jon",lastName:"snow"}
dog=person; // Property 'name' is missing in type 'Person' but required in type 'Dog'
cat=person; //Property 'name' is missing in type 'Person' but required in type 'Cat'.
Duck Typing
Duck typing is a concept in TypeScript (and other dynamically typed languages) that determines the type compatibility of an object based on its structure rather than its explicitly declared type. It's often summarized by the saying: "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck."
• Also known as "dynamic typing."
• It's based on whether an object can perform certain methods or has certain properties.
• If an object "walks like a duck and quacks like a duck," it's treated as a duck, regardless of its actual type.
• The type system doesn't care about the formal structure; it's more concerned with what the object can do.
Never Type
The never type represents the type of values that never occur. For instance, never is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns. Variables also acquire the type never when narrowed by any type guards that can never be true.
The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, never (except never itself). Even any isn’t assignable to never.
function error(message: string): never {
throw new Error(message);
}
// Inferred return type is never
function fail() {
return error("Something failed");
}
// Function returning never must not have a reachable end point
function infiniteLoop(): never {
while (true) {}
}