# Typing
> [!question] Why?
>
>Type System verifies programmers' _expectation_.
## Concepts
- Variance
- Invariance, covariant, and contra-variant for generic types.
- In [[golang|Go]] this is also referred to as "in type" and "out type".
- An in type/read-only type (for function parameter) should be covariant. An out type/write-only type (for return value) should be contra-variant. Otherwise it should be invariant.
## Flavors of Type System
### Safe/Unsafe
- Unsafe = Some operations violate _basic structure_ of program. There are
_undefined behavior_.
- Safe = Every possible operation has a _defined behavior_.
- Behaviors
- Illegal Operations (defined)
- Unpredictable
- Total chaos
### Static/Dynamic
- Static Typing: Type information is only accessed/used at compile time.
- Dynamic Typing
- Type information is stored along with the values.
- `CMP` instruction is used to type check at runtime.
- Allows user-defined types. Using a _type table_.
- Particularly useful for pulling heterogenous data.
- Gradual Typing: allowing some variables to be type-checked at compile time.
### Explicit/Implicit
- Explicit - Programmer states expectations.
- Implicit - Compiler infers the type.
### Incompatibilities
1. Disallow
2. Convert argument(s) to another type
3. Bitwise copy (almost always wrong)
4. Interpret the value in a useful way (e.g. Perl, copy vector to scalar means
length.)
### Nominal/Duck/Goose
- Nominal typing, adopted by C++, Java, C#, and *annotated* [[python|Python]]
- Duck typing, adopted by Smalltalk, Python, JavaScript, Ruby. Objects have types, variables (including parameters) are untyped. The operations supported is what matters.
- Nominal typing checks explicit inheritance, duck typing dynamically checks by invoking the operation, goose typing dynamically checks name of the methods/attribtues.