Michał Michalczuk
I am fullstack software developer #dotnet #angular #typescript, IT trainer. Both fascinated and terrified by technology advancement.
Michał Michalczuk
Ciklum / Stibo Systems
infoShare Academy
Michał Michalczuk
TypeScript
ES6
ES5
function getValue() {
switch(Math.floor(Math.random() * 10) % 3) {
case 0:
return 'foo';
case 1:
return 5;
case 2:
return { value: '5' };
default:
throw new Error('Ups');
}
}
const result = getValue() + 1;
function getValue(): any {
switch(Math.floor(Math.random() * 10) % 3) {
case 0:
return 'foo';
case 1:
return 5;
case 2:
return { value: '5' };
default:
throw new Error('Ups');
}
}
const result = getValue() as number + 1;
Lang | Types check | Run time safety |
---|---|---|
|
Dynamic | Weak |
|
Static | Weak |
|
Static | Strong |
type Order = {
clientName: string
};
const orderWorks = {} as Order;
const orderAlsoWorks = <Order>{};
I'm sure of the type, hold my bear
type Foo = {
foo: string;
handleStuff: () => void;
}
type Bar = {
foo: string;
}
const foo: Foo = {
foo: 'foo',
handleStuff: () => ({})
};
// works, struc. of `Bar` is subset
const bar: Bar = foo;
// won't compile.
// `handleStuff` is missing
foo = bar;
class Foo {
public string Foo { get; set; }
}
class Bar {
public string Foo { get; set; }
}
Foo foo = new Foo { Foo = "foo" };
// won't compile.
// Its different type
Bar bar = foo;
function handle( item: {value: string} ) {
// do stuff
}
handle({
value: 'some value'
});
const item = {
name: 'Item name',
value: 'some value',
};
handle(item);
Works
function handle( item: {value: string} ) {
// do stuff
}
// [error] Object literal may only specify known properties,
// and 'name' does not exist
// in type '{ value: string; }'.
handle({
name: 'Item name',
value: 'some value',
});
Error
Class when need to
Interface/Type aliases when need to
describe contract
do anything else
As we mentioned, type aliases can act sort of like interfaces; however, there are some subtle differences.
Interface when
Type aliases when
everything else
enum StringEnum {
One = 'One',
Two = 'Two'
}
enum NumericEnum {
One,
Two
}
var StringEnum;
(function (StringEnum) {
StringEnum["One"] = "One";
StringEnum["Two"] = "Two";
})(StringEnum || (StringEnum = {}));
var NumericEnum;
(function (NumericEnum) {
NumericEnum[NumericEnum["One"] = 0] = "One";
NumericEnum[NumericEnum["Two"] = 1] = "Two";
})(NumericEnum || (NumericEnum = {}));
.ts
.js
.d.ts
*thing which speakers need
By Michał Michalczuk
4Developers - 15.10.2018 Kraków; KarieraIT - 8.12.2018 Gdańsk
I am fullstack software developer #dotnet #angular #typescript, IT trainer. Both fascinated and terrified by technology advancement.