TypeScript Object
An object is an instance that contains a set of key-value pairs. The values can be scalars, functions, arrays, objects, etc., as in the following example:
The above object contains scalars, functions, and collections (arrays or tuples).
Object Instance
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output result is:
Example Google
TypeScript Type Template
Suppose we define an object in JavaScript:
If we want to add methods to the object, we can make the following modifications:
sites.sayHello = function(){ return "hello";}
If the above approach is used in TypeScript, a compilation error will occur, because objects in TypeScript must be instances of a specific type.
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output result is:
hello Example
In addition, an object can also be passed as a parameter to a function, as in the following example:
TypeScript
Compile the above code to get the following JavaScript code:
JavaScript
The output result is:
site1 :Example site2 :Google
Duck Typing
Duck typing (English: duck typing) is a style of dynamic typing and a form of polymorphism.
In this style, an object's valid semantics are determined not by inheriting from a specific class or implementing a specific interface, but by the "collection of current methods and properties".
It can be expressed as follows:
"When you see a bird that walks like a duck, swims like a duck, and quacks like a duck, then that bird can be called a duck."
In duck typing, the focus is on what the object's behavior can do, rather than on the type to which the object belongs. For example, in languages that do not use duck typing, we can write a function that accepts an object of type "duck" and calls its "walk" and "quack" methods. In languages that use duck typing, such a function can accept an object of any type and call its "walk" and "quack" methods. If these methods that need to be called do not exist, a runtime error will be triggered. The fact that any object with the correct "walk" and "quack" methods can be accepted by the function leads to the above expression, and this way of determining type is therefore named accordingly.