Types are becoming more important in software as programs grow larger and more complex, leading to more bugs. New types like Optional help prevent null pointer exceptions while async/await make asynchronous code more intuitive. More advanced types still being adopted include algebraic data types that model relationships between data, dependent types that allow types to depend on values, and linear types that prevent multiple uses of resources. These new types allow for stronger guarantees and more bugs caught at compile time rather than runtime.
12. AdvancedTypes
FunctionTypes
number => string :Takesinanintandreturnsastring
const f: ((n: number) => string) = function (n) {
// Do something with n.
:
return "foo";
}
Generics(Java,C#,TypeScript,etc)
function firstElement<T>(arr: T[]): T {
return arr[0];
}
16. Example(Swift):
let num: Optional<Int> = function_that_may_return_nil()
if let a = num { // Take the Int inside Optional<Int>.
print(a)
} else {
print("Was nil")
}
30. UseCases
TypeScriptExample
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
type Shape = Square | Rectangle; // Either a Square or a Rectangle.
31. TypeScriptExample(cont'd)
function non_exhaustive(s: Shape) {
switch (s.kind) {
case "square":
return s.size * s.size;
default:
const _tmp: never = s
// ^^^^ This is a compile time error!
}
return 0;
}
function not_in_part_of_the_type(s: Shape) {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
case "circle": return s.height;
// ^^^^^^^^ This is a compile time error!
}
}
49. UseCases#1
Linearresources
Files,networksockets,etc.
// Again made-up syntax. Does not actually work.
linearfunc readFile(filepath: string): string {
const fileHandle = open(filepath);
const content = readFile(fileHandle);
return content;
// Oops! Forgot to close `fileHandle`!
// Compiler can automatically emit, operation to close the handle.
}
50. UseCase#2
Performance
Ifyouknowitwon'tbeused,youcanoptimizeit.
// Again made-up syntax. TypeScript does not have this!
linearfunc f(str: string): string {
const str2 = str + "aaaaaa"; // Plain TypeScript will allocate a new memory for this.
return str2; // <- The compiler can make a decision and overwrite str in memory for performance!
}