Skip to content

Instantly share code, notes, and snippets.

View przemyslawjanpietrzak's full-sized avatar

Przemyslaw Jan Beigert przemyslawjanpietrzak

View GitHub Profile
type ReadonlyObject<A> = { readonly [K in keyof A]: A[K] };
type DeepReadonlyObject<A> = { readonly [K in keyof A]: DeepReadonly<A[K]> }
type X = DeepReadonlyObject<{ key: string, key1: number }>; // { readonly key: any; readonly key1: any; }
// @ts-check
export const fn = (arg1, arg2, arg3) => 42;
fn(1, 2, 3, 4); // ERROR Expected 3 arguments, but got 4
document.querySelector(42); // ERROR Argument of type '42' is not assignable to parameter of type 'string'.
/**
*
* @param {string} arg
* @returns {number}
const fn = (arg: unknown) => {
arg.x; // ERROR
arg > 3; // ERROR
arg + 1; // ERROR
arg.toString(); // ERROR
arg(); // ERROR
arg === null; // OK
return arg; // OK
}
// https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]"
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
interface X {
key1: string;
key2: { id: number, name: string },
key3: number;
}
const fn = (arg: X['key2']) => {
arg.id // number
arg.name // string
};
let tuple: [string, number];
tuple = ["hello", 10]; // OK
tuple = [10, "hello"]; // Error
let str = tuple[0]; // string
let num = tuple[1]; // number
@przemyslawjanpietrzak
przemyslawjanpietrzak / abstract-class.ts
Last active September 24, 2018 06:47
abstract-class
abstract class AbstractClass {
method() {
return 42
}
}
class Class extends AbstractClass {
method1() {
return 42;
}
@przemyslawjanpietrzak
przemyslawjanpietrzak / strictFunctionTypes.ts
Last active September 24, 2018 06:47
strictFunctionTypes
const fn = (arg: number, cb: (string) => string) => {
return 42
}
fn(42, a => a++); // Argument of type '(a: any) => number' is not assignable to parameter of type '(string: any) => string'. Type 'number' is not assignable to type 'string'.
@przemyslawjanpietrzak
przemyslawjanpietrzak / ampersand.ts
Last active September 24, 2018 06:48
ts-ampersand
const fn = (arg: { key: string } & { key1: number }) => 42;
fn({ key: '42' }); // ERROR
fn({ key1: 42 }); // ERROR
fn({ key: '42', key1: 42 }); // GOOD
// GOOD
const fn = (arg: { [key: string]: number }) => {
const val = arg.key1 + arg.key2 + arg.key3; // number
const val1 = arg.totallyRandomKey; // number
const val2 = arg['wpłynąłem na suchego przestwór oceanu']; // number
};