function test(msg: string, func?: (m: string)=>void) {
func?.(a, b);
}
test('nothing');
test('something', (m)=>console.log(m));
Search This Blog
Showing posts with label typescript. Show all posts
Showing posts with label typescript. Show all posts
Typescript optional function
Typescript array elements map to objects
interface Person { name: string; email?: string }
array.map(val => <Person> {
name: val.key1,
email: val.key2
});
Javascript: remove trailing zeros returned by toFixed()
const n = 12000; console.log((n/1000).toFixed(3)); # 12.000 console.log(parseFloat((n/1000).toFixed(3))); # 12
See also
Javascript: sort string array alphabetically
localeCompare() method can be used:
const array = ['b', 'd', 'c', 'a']; array.sort((a,b)=>a.localeCompare(b));
see also
Javascript: remove duplicated values from array
Get distinct values from Array
let array = ['aaa', 'bbb', 'ccc', 'bbb', 'ddd']; console.log(array); array = Array.from(new Set(array)); console.log(array);
Get distinct values from Map
const map = new Map<string, number>();
map.set('foo', 1);
map.set('bar', 2);
map.set'zoo', 1);
const distinctValues = Array.from(new Set(map.values()));
see also
Javascript: access object property
const obj = { name: 'John Foo', email: 'john.foo@aaa.com' };
let prop = 'name';
console.log(obj[prop]); // 'John Foo'
prop = 'email';
console.log(obj[prop]); // 'john.foo@aaa.com'
See also
Javascript: number to string
- Javascript/Typescript:
const n = 1; const s1 = '' + 1; console.log(typeof s1); // string console.log(s1); // '1' const s2 = String(n); console.log(typeof s2); // string console.log(s2); // '1'
- Typescript:
const n = 1; const s1 = <string><any>n; console.log(typeof s1); // string console.log(s1); // '1' const s2 = n as any as string; console.log(typeof s2); // string console.log(s2); // '1'
see also
Javascript: check variable type
const a = 1; const b = '2'; console.log(typeof a); // 'number' console.log(typeof a === 'number'); // true console.log(typeof b); // 'string' console.log(typeof b === 'string'); // true
Javascript: find all matches
const regex = /([^\/]+):/g;
const s = 'MMM:mmm/AAA:aaa/BBB:bbb/ccc';
let m;
while(m = regex.exec(s)) {
console.log(m[0], m[1]);
}
see also
Styling React App with Emotion
- Install Emotion packages into your React App by running the command inside the React project directory:
npm install --save @emotion/react @emotion/styled
- Add following to tsconfig.json
{ "compilerOptions": { ... "jsx": "react-jsx", "jsxImportSource": "@emotion/react", ... } } - At the top of your .tsx file, insert line:
/** @jsxImportSource @emotion/react */
see also
- TS2322: Property 'css' does not exist...
- Emotion CSS Prop and Nextjs new JSX runtime - error: pragma and pragmaFrag cannot be set when runtime is automatic
- https://mudandmoss.medium.com/solving-you-have-tried-to-stringify-object-returned-from-css-function-error-from-emotion-in-react-50b3a70ed650
- Emotion: Using both a class and the "css" method in "className" prop
Date.parse() behaves different in Firefox compared with Chrome for 'dd-MMM-yyyy'
Date.parse('12-Jan-2022'); works fine in Chrome/Edge, however, Firefox returns wrong date.
To parse the string in Firefox, I wrote my own parser in Typescript:
export function parseDate(ds: string): Date {
const regexDateOnly = /^\d{1,2}-[ADFJMNOS]{1}[abceglnoprtuvy]{2}-\d{4}$/g;
const regexDateTime = /^\d{1,2}-[ADFJMNOS]{1}[abceglnoprtuvy]{2}-\d{4} \d{2}:\d{2}:\d{2}$/g;
const regexDateTimeMilliSecs = /^\d{1,2}-[ADFJMNOS]{1}[abceglnoprtuvy]{2}-\d{4} \d{2}:\d{2}:\d{2}\.\d{3}$/g;
let datePart = '';
let timePart = '';
let millisPart = '';
if (regexDateTimeMilliSecs.test(ds)) {
const parts1 = ds.split(' ');
const parts2 = parts1[1].split('.');
datePart = parts1[0];
timePart = parts2[0];
millisPart = parts2[1];
} else if (regexDateTime.test(ds)) {
const parts = ds.split(' ');
datePart = parts[0];
timePart = parts[1];
} else if (regexDateOnly.test(ds)) {
datePart = ds;
} else {
throw new Error(`Failed to parse date: ${ds}`)
}
let year = 1970, month = 0, day = 1, hour = 0, minute = 0, second = 0, millisecs = 0;
if (datePart) {
const parts = datePart.split('-');
day = parseInt(parts[0]);
switch (parts[1].toLowerCase()) {
case 'jan':
month = 0;
break;
case 'feb':
month = 1;
break;
case 'mar':
month = 2;
break;
case 'apr':
month = 3;
break;
case 'may':
month = 4;
break;
case 'jun':
month = 5;
break;
case 'jul':
month = 6;
break;
case 'aug':
month = 7;
break;
case 'sep':
month = 8;
break;
case 'oct':
month = 9;
break;
case 'nov':
month = 10;
break;
case 'dec':
month = 11;
break;
default:
break;
}
year = parseInt(parts[2]);
}
if (timePart) {
const parts = timePart.split(':');
hour = parseInt(parts[0]);
minute = parseInt(parts[1]);
second = parseInt(parts[2]);
}
if (millisPart) {
millisecs = parseInt(millisPart);
}
return new Date(year, month, day, hour, minute, second, millisecs);
}
see also
Material UI DataGrid: set Footer selected count information
<DataGrid
localeText={{
footerRowSelected: (count) => `${count} files selected`
}} />
See also
Setup Svelte Material UI
- Install svelte-preprocess
npm install -D svelte-preprocess
- Install any Svelte Material UI comonent:
npm install --save-dev @smui/button
Note: you need to install at least one component otherwise you cannot compile the theme css. - Install smui-theme and create a template at src/theme
npm install -D smui-theme npx smui-theme template src/theme
- Add following script to scripts section of package.json
"prepare": "smui-theme compile public/build/smui.css -i src/theme"
- Compile the css from smui-theme template:
npm run prepare
It should create public/build/smui.css - Add the compiled css to public/index.html file:
<link rel='stylesheet' href='/build/smui.css'>
- Add Material Fonts to public/index.html
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<!-- Roboto -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,600,700"
/>
<!-- Roboto Mono -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto+Mono"
/>
Set up http proxy for Svelte web app using rollup-plugin-dev
- Install rollup-plugin-dev:
npm install -D rollup-plugin-dev
- Modify rollup.config.js:
import dev from 'rollup-plugin-dev'; ... ... export default { ... ... plugins: [ ... ... !production && dev({ host: 'localhost', port: 5000, dirs: ['public'], proxy: [{ from: '/__mflux_svc__', to: 'http://localhost:8086' }] }), // !production && serve(), ... ... ] }
see also
Create a Svelte Typescript app from rollup template
- Initialize Svelte Web App:
npx degit sveltejs/template svelte-ts-app cd svelte-ts-app node scripts/setupTypeScript.js npm install
- [Optional] Install rollup-plugin-dev to enable http proxy
- [Optional] Setup Svelte Material UI components
- Starts rollup dev mode:
npm run dev
- Building and running in production mode:
npm run dev npm run start
see also
Typescript development setup with Visual Studio Code
- Install node.js
- Install node.js modules: typescript and tslint globally:
npm install -g typescript tslint
- Install Visual Studio Code extensions: "TSLint" and "Debugger for Chrome"
- Start Visual Studio Code
- CMD+SHIFT+P (CTRL+SHIFT+P) then type: Extensions, select "Extensions: Install Extensions"
- Search and install "Debugger for Chrome" and "TSLint" extensions
- Initialize project/workspace directory:
mkdir HelloWorld cd HelloWorld tsc --init
It will create tsconfig.json file in the project/workspace directory. - open HelloWorld folder in Visual Studio Code, and edit tsconfig.json file:
{ "compilerOptions": { "target": "es5", "module": "commonjs", "lib": [ "es2015.promise", /* Promise */ "dom" ], "sourceMap": true, "outDir": "./", } } - Create index.html file:
<!DOCTYPE html> <html> <head> <title>Hello Typescript</title> </head> <body> <h1>Fun with TypeScript</h1> <p id="index">Let's rock</p> <script src="main.js"> </script> </body> </html> - Create main.ts file:
function hello() { console.log('Hello'); alert('hello'); } hello(); - Configure Default Build Task
- Open the command palette using CMD+SHIFT+P (CTRL+SHIFT+P) and type "Tasks", then select "Configure Default Build Task...", then select "tsc:watch".
- It will create .vscode/tasks.json file.
- tsc:watch runs automatically when you change a TypeScript file.)
- Run Build Task
- CMD+SHIFT+B (CTRL+SHIFT+B) to build.
- It generates main.js and main.js.map files.
- Debugging setup
- CMD+SHIFT+P (CTRL+SHIFT+P) and select "Debuging: Start Debugging", then select "Chrome"
- It should create .vscode/launch.json, edit the file:
{ "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Launch Chrome against localhost", "url": "http://localhost:8086/HelloWorld/index.html", "webRoot": "${workspaceFolder}", "userDataDir": "/tmp/chrome-debug", } ] } - Set some breakpoint in the main.ts, then CMD+SHIFT+P and "Debuging: Restart Debugging", see if it stops at the breakpoint.
- Directory structure:
HelloWorld/ HelloWorld/.vscode/ HelloWorld/.vscode/launch.json HelloWorld/.vscode/settings.json HelloWorld/.vscode/tasks.json HelloWorld/index.html HelloWorld/main.ts HelloWorld/main.js HelloWorld/main.ts.map HelloWorld/tsconfig.json
Project/Workspace settings are saved in .vscode/settings.json
See also
Subscribe to:
Posts (Atom)