<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ashok Khanna on Medium]]></title>
        <description><![CDATA[Stories by Ashok Khanna on Medium]]></description>
        <link>https://medium.com/@ashok-khanna?source=rss-81f1c825fc12------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xfU-AcbKxxVOO8bTBILTpA.jpeg</url>
            <title>Stories by Ashok Khanna on Medium</title>
            <link>https://medium.com/@ashok-khanna?source=rss-81f1c825fc12------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:29:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashok-khanna/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introduction to TypeScript (Part 4)]]></title>
            <link>https://ashok-khanna.medium.com/introduction-to-typescript-part-4-e9e9ea3f102c?source=rss-81f1c825fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9e9ea3f102c</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ashok Khanna]]></dc:creator>
            <pubDate>Sun, 29 May 2022 11:43:25 GMT</pubDate>
            <atom:updated>2022-05-29T11:43:25.585Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 4 of a Four-Part Guide for Experienced JavaScript Developer</h4><p>Welcome to the last part in our four-part guide on TypeScript!</p><p>In <a href="https://ashok-khanna.medium.com/introduction-to-typescript-c3fd1374fd90">Part 1 we introduced the basic concepts of TypeScript</a>, in <a href="https://ashok-khanna.medium.com/introduction-to-typescript-part-2-d3c755300d5d">Part 2 we stressed how to think in TypeScript</a>, whilst in <a href="https://ashok-khanna.medium.com/introduction-to-typescript-part-3-99071f1758c">Part 3 we covered many useful concepts for function, object and class typing</a>. We are now in the home stretch and will cover the slightly advanced but ultimately very central concept of generic types and type manipulation.</p><p>The main aim of generic typing and type manipulation is to express complex operations and values in a succinct, <strong><em>maintainable</em></strong> way (picture yourself refactoring entire modules and wanting to cascade down changes .</p><h3>Generic Types</h3><p>It’s common to write a function where the types of the input relate to the type of the output, or where the types of two inputs are related in some way. In TypeScript, <strong><em>generics</em></strong> are used when we want to describe a correspondence between two values. We do this by declaring a <strong><em>type parameter</em></strong> in the function / object / class signature.</p><h4>Generic Functions</h4><p>Below is an example of a generic function that utilises a generic type.</p><pre>function firstElement<strong>&lt;Type&gt;</strong>(arr: <strong>Type</strong>[]): <strong>Type</strong> | undefined {<br>  return arr[0];<br>}</pre><p>By adding a type parameter Type to this function and using it in two places, we’ve created a link between the input of the function (the array) and the output (the return value). Now when we call it, a more specific type comes out:</p><pre>// In the below s is of type &#39;string&#39;:<br>const s = firstElement([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]);</pre><pre>// In the below n is of type &#39;number&#39;<br>const n = firstElement([1, 2, 3])</pre><pre>// In the below u is of type &#39;undefined&#39;<br>const u = firstElement[]</pre><h4>Type Inference</h4><p>What is especially interesting in the above examples is that we did not have to specify the type when calling the generic function — TypeScript can infer the type from the arguments passed in.</p><h4>Multiple Generic Types</h4><p>Note that we can have multiple generic types within a type signature:</p><pre>function map&lt;<strong>Input, Output</strong>&gt;(arr: Input[], func: (arg: Input) =&gt; Output): Output[] {<br>  return arr.map(func);<br>}</pre><h4>Constraining Generic Types</h4><p>In the above examples, any type could be used in palce of the generic. If we want to constrain the generic type, we do something the following. In this example, the generic type must have the property length:</p><pre>function longest&lt;Type <strong>extends</strong> { length: number }&gt;(a: Type, b: Type) {<br>  if (a.length &gt;= b.length) {<br>    return a;<br>  } else {<br>    return b;<br>  }<br>}</pre><h4>Note about Using Generic Types &amp; Functions</h4><p>Writing generic functions is fun, but don’t forget their purpose — to observe and annotate a <strong><em>relationship </em></strong>between multiple types in a signature. If this is not present, then there isn’t much point to using generics and as a golden rule <strong><em>generic type parameters should appear at least twice in a type declaration</em></strong>.</p><p>As an aside, this is an important reflection about TypeScript itself. The language is meant for adding additional information about what values can and can’t be accepted in various concepts, that is not readily inferred from the code itself. By doing so, we increase the robustness of our code (due to static type checking) and make it easier for others (or ourselves in the future) to understand what is going on as we are explicitly narrowing down and documenting the possible paths various programming flows can take.</p><h4>Some more notes on Generic Functions</h4><p>The below is an illustrative example of how the placement of the generic Type affects its meaning.</p><pre>interface GenericFunction1&lt;Type&gt; {<br>  (arg: Type): Type<br>}</pre><pre>interface GenericFunction2 {<br>  &lt;Type&gt;(arg: Type): Type;<br>}</pre><p>Note how the placement of the generic Type modifies the meaning of these declarations:</p><pre>// myFunction1 must accept arguments of type number</pre><pre>let myFunction1: GenericFunction1&lt;Number&gt;</pre><pre>// myFunction2 must return the same argument as that passed in</pre><pre>myFunction2: GenericFunction2</pre><h4>Generic Object Types</h4><p>Back to learning TypeScript syntax, lets start looking at how we can use generics in other contexts. First up, we can define generic interfaces and types as follows.</p><pre>interface Box&lt;Type&gt; { contents: Type }</pre><pre>type Box&lt;Type&gt; = { contents: Type }</pre><pre>// Either of the above will allow you to do:<br>let box: Box&lt;string&gt;</pre><p>Note that since type aliases, unlike interfaces, can describe more than just object types, we can also use them to write other kinds of generic helper types.</p><pre>type OrNull&lt;Type&gt; = Type | null;<br><br>type OneOrMany&lt;Type&gt; = Type | Type[];<br><br>type OneOrManyOrNull&lt;Type&gt; = OrNull&lt;OneOrMany&lt;Type&gt;&gt;;<br><br>type OneOrManyOrNull&lt;Type&gt; = OneOrMany&lt;Type&gt; | null<br><br>type OneOrManyOrNullStrings = OneOrManyOrNull&lt;string&gt;;<br><br>type OneOrManyOrNullStrings = OneOrMany&lt;string&gt; | null</pre><h4>Array Types</h4><p>You can now hopefully see that Array&lt;number&gt; and Array&lt;string&gt; are generic types, whose equivalent shorthands are number[] and string[].</p><h4>Generic Classes</h4><p>Below is an example of a generic class, following similar syntax as the above. When a generic class is instantiated with new, its type parameters are inferred the same way as in a function call.</p><pre><br>class Box&lt;<strong>Type, NumType</strong>&gt; {<br>  contents: <strong>Type</strong>;<br>  add: (x: <strong>NumType</strong>, y: <strong>NumType</strong>) =&gt; <strong>NumType</strong>;</pre><pre>  constructor(value: <strong>Type</strong>) {<br>    this.contents = value;<br>  }<br>}<br><br>const b = new Box(&quot;hello!&quot;);</pre><h3>Type Manipulation</h3><p>Type Manipluation is a related concept to generic types. TypeScript provides us a way to express types in terms of more primitive types, and similar to how we abstract away our code into modules and components, allow us to do the same with types — effectively type programming. The benefit of this is twofold:</p><ul><li>By combining various types to express complex operations, we make our type system very maintable as we can modify certain parts and allow the changes to cascade down to all other types that rely on those parts</li><li>The more specialised our types get, the more bugs and incorrect programming flows we can pick up at compile time and not run time. This helps make our programs more robust (although type checking is not a panacea for all runtime bugs — just a tool to help reduce them)</li></ul><p>We already discussed generic types, and these are used heavily in building our own custom types and type systems. We will discuss some additional building blocks here. Note that some of these ideas are a bit advanced, so feel free to refer back to them when you are more familiar with TypeScript. Also note that all these ideas (and indeed everything in this four-part guide) are meant to be combined with each other — take these building blocks and build something beautiful! By themselves, they do look a bit disjointed but think of the possiblities.</p><h4>Keyof Type Operator</h4><p>The keyof operator takes an object type and produces a string or numeric literal union of its key:</p><pre>type Point = { x: number; y: number };</pre><pre>// This is the same as type p = &quot;x&quot; | &quot;y&quot;<br>type P = keyof Point;</pre><p>If the type has a string or number index signature, keyof will return those types instead:</p><pre>type Arrayish = { [n: number]: unknown };</pre><pre>// same as type A = number;<br>type A = keyof Arrayish;</pre><h4>Typeof Type Operator</h4><p>We can use the typeof operator in a <strong><em>type context</em></strong> to refer to the type of a variable or property:</p><pre>let s = &quot;hello&quot;;</pre><pre>// same as let n: string<br>let n: typeof s;</pre><h4>Indexed Access Types</h4><p>We can use an indexed access type to get the type of a property on another type (note the last example of how we start combining multiple type concepts together — try other combinations yourself too!):</p><pre>type Person = { age: number; name: string; alive: boolean };</pre><pre>// Same as type Age = number<br>type Age = Person[&quot;age&quot;];</pre><pre>// Same as type I1 = string | number<br>type I1 = Person[&quot;age&quot; | &quot;name&quot;];</pre><pre>// Same as type I2 = string | number | boolean<br>type I2 = Person[keyof Person];</pre><p>We can use number to get the type of an array’s elements, combining it with the typeof operator:</p><pre>const MyArray = [ { name: &quot;Alice&quot;, age: 15 },<br>                  { name: &quot;Bob&quot;, age: 23 },<br>                  { name: &quot;Eve&quot;, age: 38 }, ];</pre><pre>// Same as type Person = { name: string, age: number }<br>type Person = typeof MyArray[number];</pre><pre>// Same as type Age = number<br>type Age = typeof MyArray[number][&quot;age&quot;]</pre><h4>Conditional Types</h4><p><a href="https://www.typescriptlang.org/docs/handbook/2/conditional-types.html">Conditional types</a> help describe the relation between the types of inputs and outputs. They take the form of SomeType extends OtherType ? TrueType : FalseType:</p><pre>type Example1 = Dog extends Animal ? number : string;</pre><p>In the above example, when Dog is assignable to Animal then Example1 has type number, otherwise it has type string.</p><p>There are some more points when it comes to conditional types (e.g. using the infer operator), but we’ll stop here for now and refer you to the<a href="https://www.typescriptlang.org/docs/handbook/2/conditional-types.html"> official documentation when you are ready to dig into these further</a>.</p><h4>Mapped &amp; Template Literal Types</h4><p>Once you get more familiar with TypeScript and start using it more (remember — don’t worry if you don’t use every concept at the start, just start coding in TypeScript and you will naturally improve over time and tighten your static typing), it is worthwhile reading about <a href="https://www.typescriptlang.org/docs/handbook/2/mapped-types.html">mapped types</a> and <a href="https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html">template literal types</a>.</p><h3>Rounding it Out: Importing &amp; Exporting Types</h3><p>To round out this part (and the entire guide!), lets show how to import and export types across files. Fortunately, it is much in the same way as importing and exporting in modern ECMAScript:</p><pre>export type Cat = { breed: string; yearOfBirth: number };</pre><pre>import type { Cat, Dog } from &quot;./animal.js&quot;;</pre><h3>Conclusion</h3><p>We have now reached the end of our four part guide. Hopefully some of it makes sense. The best way to learn is to use TypeScript, so do try and use it in your projects and hopefully within a few days or weeks you will start to appreciate how good it is and why I went to the trouble of writing this guide to encourage you to use it. I really enjoy programming in TypeScript and hope you do too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9e9ea3f102c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to TypeScript (Part 3)]]></title>
            <link>https://ashok-khanna.medium.com/introduction-to-typescript-part-3-99071f1758c?source=rss-81f1c825fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/99071f1758c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ashok Khanna]]></dc:creator>
            <pubDate>Sun, 29 May 2022 10:12:44 GMT</pubDate>
            <atom:updated>2022-05-29T11:45:01.585Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3 of a Four-Part Guide for Experienced JavaScript Developers</h4><p><a href="https://ashok-khanna.medium.com/introduction-to-typescript-part-2-d3c755300d5d">In Part 2, we covered parameter deconstructions, type guards and type assertions</a>, which are relatively simple concepts, but helped point us towards a path of thinking in TypeScript. In this Part, we will cover many useful concepts around the typing of functions, objects and classes.</p><h3>Function Typing</h3><p>We covered the <a href="https://ashok-khanna.medium.com/introduction-to-typescript-c3fd1374fd90">basics of Function Typing in Part 1</a>, but let us cover some additional topics like optional parameters and function overloading.</p><h4>Optional Parameters</h4><p>An interesting point about JavaScript is that functions can take a variable number of arguments. Paraphrasing the ECMA standard</p><ul><li>If a function or constructor is given fewer arguments than required, the function or constructor shall behave exactly as if it had been given sufficient additional arguments, each such argument being the undefined value</li><li>If a function or constructor described in this clause is given more arguments than specified, the extra arguments are evaluated by the call and then ignored by the function</li></ul><p>We can handle optional parameters in TypeScript in two ways. Like in other languages, we can denote parameters as optionals with the use of the ? operator:</p><pre>function f(x?: number) { ... }</pre><p>An alternate way is to simply supply a default value for the parameter (which will be used in the parameter is not passed through in a function call):</p><pre>function f(x = 5) { ... }</pre><p>The above concepts of optional types and default values apply to properties in objects and classes as well.</p><h4>Function Overloading</h4><p>This leads us to our next concept of function overloading. This is something where TypeScript does differ slightly from JavaScript as the first two items below represent overload signatures and would not be valid JavaScript otherwise (think of them as akin to type declarations, with a different syntax):</p><pre>// Function Signatures - Deleted from TypeScript during transpilation</pre><pre>function makeDate(timestamp: number): Date;</pre><pre>function makeDate(m: number, d: number, y: number): Date;</pre><pre>// Function implementation - what gets used in JavaScript</pre><pre>function makeDate(mOrTimestamp: number, d?: number, y?: number): Date {<br>  // implementation<br>}</pre><p>The TypeScript Reference Manual notes that we should prefer union types over function overloads where possible.</p><h4>Function Type Expressions</h4><p>We round out this section by quickly showcasing how you can create function type expressions (<strong>bolded parts below</strong>), which are useful when typing functional parameters:</p><pre>function greeter(fn: <strong>(a: string) =&gt; void</strong>) {<br>  fn(&quot;Hello, World!&quot;);<br>}</pre><pre>// or alternatively</pre><pre>type GreeterFunction = <strong>(a: string) =&gt; void</strong></pre><pre><br>// Then utilising these:</pre><pre>function greeter(fn:  GreetFunction) { ... }</pre><h3>Object Typing</h3><h4>Index Signatures</h4><p>Sometimes we want to restrict the keys of objects or arrays to either string or numbers (usually they can be both) and/or restrict the type of objects contained within them (we can restrict to any type). We can do that with an index signature as follows:</p><pre>interface StringArray { [index: number]: string; }</pre><pre>// or</pre><pre>type NumberArrayWithStringKeys { [index: string: number ;}</pre><pre>// another example</pre><pre>type OnlyBooksArray { [index: string]: Book; }</pre><h4>Readonly Properties</h4><p>We mark object properties as readonly with the following:</p><pre>interface SomeType { readonly prop: string }</pre><h4>Intersection Types</h4><p>If we want a type to have all the properties of two component types, we can use the &amp; operator:</p><pre>type ColorfulCircle = Colorful &amp; Circle;</pre><h4>Extending Types</h4><p>We can extend object types (i.e. create a more specific version that has extra properties) with the extends keyword:</p><pre>interface AddressWithUnit extends BasicAddress {<br>  unit: string;<br>}</pre><p>Note that we use extends with interface and &amp; with type aliases to achieve something similar. <a href="https://stackoverflow.com/questions/42735611/why-can-intersection-types-contain-conflicting-types">There are some subtle differences on how conflicts are handled</a>.</p><h4>Tuple Types</h4><p>Below are examples of tuples types in action. Tuple types are useful in heavily convention-based APIs, where each element’s meaning is “obvious”. This gives us flexibility in whatever we want to name our variables when we destructure them.</p><pre>type StringNumberPair = [string, number]</pre><pre>function doSomething(pair: [string, number]){<br>  // Both are equivalent<br>  const [a, b] = pair;</pre><pre>  a = pair[0];<br>  b = pair[1];</pre><pre>  ..do something with a &amp; b<br>}</pre><h3>Class Typing</h3><h4>Abstract Types</h4><p>Classes, methods and fields in TypeScript may be abstract, which means they do not have any provided implementation and must exist inside an abstract class which cannot be directly instantiated. The role of abstract classes is to serve as a base class for subclasses which do implement all the<br>abstract members. When a class doesn’t have any abstract members, it is said to be concrete.</p><pre>abstract class Base {<br>  abstract getName(): string;<br><br>  printName() {<br>    console.log(&quot;Hello, &quot; + this.getName());<br>  }<br>}</pre><pre>const b = new Base(); // Error<br><br>class Derived extends Base {<br>  getName() {<br>    return &quot;world&quot;;<br>  }<br>}<br><br>const d = new Derived(); // Okay</pre><h4>Implementing Interfaces</h4><p>You can use an implements clause to check that a class satisfies a particular interface. It’s important to understand that an implements clause is only a check that the class can be treated as the interface type. It doesn’t change the type of the class or its methods at all.</p><pre>interface Pingable {<br>  ping(): void;<br>}<br><br>class Sonar implements Pingable {<br>  ping() {<br>    console.log(&quot;ping!&quot;);<br>  }</pre><h4>Public, Private and Protected Class Members</h4><p>public members can be accessed anywhere, private members can only be accessed within the class whilst protected members are only accessible within the class and its subclasses.</p><pre>class Base {<br>  private x = 0; // &lt;-- Only the Base class can access</pre><pre>  public printX() { console.log(x); } &lt;-- Anybody can call this</pre><pre>  protected greeting() { console.log(&quot;Hi&quot;) } &lt;-- Subclasses can call<br>}</pre><p>The default visibility of class members is public. These visibility modifiers also work on static members (e.g. private static x = 0).</p><h4>The “this” keyword in TypeScript</h4><p>The this keyword in JavaScript &amp; TypeScript can be confusing at times, and I won’t try and explain it here (I myself am not very good with it). <a href="https://www.typescriptlang.org/docs/handbook/2/classes.html#this-at-runtime-in-classes">You can read more about it here</a>.</p><h4>Constructor Shorthand in TypeScript</h4><p>One way in which TypeScript adds to JavaScript is providing the below shorthand for class constructors (note that this would be otherwise illegal JavaScript code if we simply stripped out the types):</p><pre>class Params {<br><strong>  constructor(public readonly x: number, protected y: number,<br>              private z: number)</strong> {<br>    // No body necessary<br>  }<br>}</pre><h3>Rounding it Out: Structural Comparisons</h3><p>To add one final comment before we round out Part 3, note that TypeScript compares classes and other types <strong><em>structurally</em></strong> in the sense that the below two classes can be used in place of each other because they are identical structurally:</p><pre>class Point1 {  x = 0;  y = 0; }<br><br>class Point2 {  x = 0;  y = 0; }<br><br>// OK<br>const p: Point1 = new Point2();</pre><p>Similarly, TypeScript will implicitly regard a subtype relationship to exist between the following two classes, despite no explicit inheritance:</p><pre>class Person {<br>  name: string;<br>  age: number;<br>}<br><br>class Employee {<br>  name: string;<br>  age: number;<br>  salary: number;<br>}<br><br>// OK<br>const p: Person = new Employee();</pre><h3>Next Steps</h3><p>This part was a very practical look at function, object and class types and we are now relatively well placed in our understanding TypeScript. <a href="https://ashok-khanna.medium.com/introduction-to-typescript-part-4-e9e9ea3f102c">In the final part 4, we will discuss generic types and how to create and manipulate our own custom types</a>. These tools are helpful in adding more specific typing to our code and also making our types build upon each other so that we can refactor our types with greater ease (useful as our programs get larger). Think of it as a chapter in Type Programming. Take a quick break and lets march on over to the finish line!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99071f1758c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to TypeScript (Part 2)]]></title>
            <link>https://ashok-khanna.medium.com/introduction-to-typescript-part-2-d3c755300d5d?source=rss-81f1c825fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3c755300d5d</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ashok Khanna]]></dc:creator>
            <pubDate>Sun, 29 May 2022 08:25:15 GMT</pubDate>
            <atom:updated>2022-05-29T10:17:47.315Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2 of a Four-Part Guide for Experienced JavaScript Developers</h4><p>We introduced some <a href="https://medium.com/@ashok-khanna/introduction-to-typescript-c3fd1374fd90">basic concepts of TypeScript in Part 1</a>, but will now take our understanding to another level. The goal of this part is to make you start <strong><em>thinking</em></strong> in TypeScript.</p><p>To do that, we need to understand what TypeScript is. We mentioned in Part 1 that it is a syntactical superset of JavaScript — all JavaScript code is equally valid in TypeScript. The important implication of this is that <strong><em>TypeScript syntax cannot interfere with JavaScript syntax</em></strong>.</p><p>For example, in JavaScript, the below bolded deconstruction is used to map the properties first and second in the incoming object to firstName and secondName within the function.</p><pre>function printName(<strong>{first: firstName, second: secondName}</strong>) {<br>  console.log(&quot;Hello, &quot; + firstName + &quot; &quot; + secondName);<br>}</pre><pre>printName({first: &quot;Ashok&quot;, second: &quot;Khanna&quot;});</pre><p>Given how natural TypeScript feels, we would have naturally expected the below to work:</p><pre>function printName({first: string, second: string}) { ... }</pre><p>This will obviously not work due to JavaScript’s use of this syntax pattern. Rather, we need to do this:</p><pre>function printName({first, second}: {first: string, second: string})</pre><p>Thus, the first golden rule when thinking in TypeScript is that we should never interfere or violate syntax in JavaScript. TypeScript is an add-on that improves JavaScript but it does not change its core syntax or functionality.</p><h4>Understanding how the TypeScript Compiler Works</h4><p>This leads us to our next point — how the TypeScript compiler transpiles TS to JavaScript. By and large (with a few minor exceptions), TypeScript does not add any new features to JavaScript apart from Typing. The TypeScript compiler, after validating all type checks, typically <strong><em>deletes</em></strong> all typing information to convert a TypeScript .ts file to a JavaScript .js file.</p><p>For example, the below conversion will occur in the transpilation:</p><pre>// TypeScript Code:<br>const x: number = 10;<br>const y: number = 20;</pre><pre>function add(x: number, y: number): number {<br>  return x + y;<br>}</pre><pre>// Transpiled JavaScript Code:<br>const x = 10;<br>const y = 20;</pre><pre>function add(x, y) {<br>  return x + y;<br>}</pre><p>Thus, when thinking in TypeScript be mindful of two golden rules:</p><ul><li>Never write anything that would interfere or violate JavaScript syntax</li><li>Never expect anything more from TypeScript than static type checking. Imagine your code without the type annotations and ensure it is written in a way that it will work without them (fortunately, TypeScript will give you enough errors to remind you of this point, the next section being an insightful example)</li></ul><h3>Intermediate Topic 1: Type Guarding</h3><p>JavaScript has the function typeof which can be used to query the type of an object at runtime. It can return one of eight values: “string”, “number”, “bigint”, “boolean”, “symbol”, “undefined”, “object” and “function”:</p><pre>if (typeof strs === &quot;object&quot;) { ... }<br>if (typeof strs === &quot;string&quot;) { ... }</pre><p>Note that null is actually of type Object, so if we want to guard against nulls, we would do something like the following, taking advantage of JavaScript’s implicit coercion of 0, -0, NaN, &quot;&quot;, 0n, undefined and null to false:</p><pre>if (strs &amp;&amp; typeof strs === &quot;object&quot;) { ... }</pre><p>Naturally, TypeScript can make use of typeof to <strong><em>narrow</em></strong> down union types such as string | boolean and ensure each case is handled correctly:</p><pre>function test(object: string | boolean) {<br>  if (typeof object === &quot;string&quot;) {<br>    console.log(object.toUpperCase());<br>  } else {<br>    console.log(object);<br>  }<br>}</pre><p>This is a very common pattern that one may use in TypeScript, and in this instance, TypeScript is helpful in reminding you to add <strong><em>type guards</em></strong> to ensure each type of input is handled correctly at runtime.</p><p>We would expect something similar for our user-defined types, however this is not possible. Both of the below would not work as intended:</p><pre>if (typeof object === &quot;string&quot; | &quot;boolean&quot;) { ... }<br>if (typeof objet === &quot;fish&quot;) { ... }</pre><p>Rather, we need to stay within the realms of JavaScript (remember TypeScript doesn’t do anything funky, it just adds some type annotations to otherwise legal JavaScript code), such as in the following. Here we use a type predicate (taking the form <strong><em>parameterName is Type</em></strong>) and a type assertion (taking the form <strong><em>parameter as Type</em></strong>) in an otherwise legal JavaScript function that simply tests for whether the required property is present on the object:</p><pre>function isFish(pet: Fish | Bird): <strong>pet is Fish</strong> {<br>  return (<strong>pet as Fish</strong>).swim !== undefined;<br>}</pre><pre>if (isFish(pet)) {<br>  pet.swim();<br>} else {<br>    pet.fly();<br>}</pre><p>Note how you could write the above type guard simply as the following, and how we use the presence of the swim property as the defining attribute for the type Fish. All is plain JavaScript — the type assertions and predicates in the above simply help TypeScript and its compiler to notify them of this definition, but do not modify the core JavaScript semantics.</p><pre>function isFish(pet) { return pet.swim !== undefined; }</pre><p>I hope this long-winded discussion has helped stress that you need to think in terms of legal JavaScript code and use TypeScript as an annotation and type checking engine and not some special language that transforms otherwise illegal JavaScript code into legal JavaScript code (as mentioned earlier, there a few edge cases where TypeScript does do some real transformations — we will get to those in due course).</p><h3>Intermediate Topic 2: Type Assertions</h3><h4>Type Assertions</h4><p>Type assertions, which we mentioned briefly above, allow us to convert to a more specific or less specific version of a type and are often used when working with DOM elements where we know more information than the compiler. They can be achieved with the as keyword or with &lt;&gt; as the following two equivalent examples show.</p><pre>const myCanvas = document.getElementById(&quot;main_canvas&quot;) as HTMLCanvasElement;</pre><pre>const myCanvas = &lt;HTMLCanvasElement&gt;document.getElementById(&quot;main_canvas&quot;);</pre><p>Note the below would be illegal as string and number are not more specific / less specific from each other:</p><pre>const x = &quot;hello&quot; as number;</pre><p>In the rare instance where this rule may be too onerous, one can assert to any and then to the required type:</p><pre>const a = (expression as any) as boolean;</pre><p>One other thing I wanted to mention is that we can remove null and defined types from a type without any explicit checking with the ! operator:</p><pre>console.log(x!.toFixed());</pre><h3>Rounding it Out: Some Miscallenous Types</h3><p>To round out Part 2, we will touch upon some miscellaneous types in TypeScript. One thing to note with TypeScript is that the language is made up of a small number of concepts which can be combined in powerful ways. So whilst I am showing you some of the main concepts, start thinking about how and why you may want to combine them.</p><p>Lets quickly mention some additional types in TypeScript:</p><ul><li>The object type refers to any value that isn’t a primitive (string, number,<br>bigint, boolean, symbol, null, or undefined). This is different from the empty object type{}, and also different from the global type Object. It’s very likely you will never use Object</li><li>The unknown type represents any value. This is similar to the any type, but is safer because it’s not legal to do anything with an unknown value</li><li>The never type represents values which are never observed. In a return type, this means that the function throws an exception or terminates execution of the program</li><li>The global type Function describes properties like bind, call, apply, and others present on all function values in JavaScript. It also has the special property that values of type Function can always be called; these calls return any</li></ul><h3>Next Steps</h3><p>You are well on your way to learning TypeScript. Hopefully these explanations have been relatively straightforward, but I do warn you that it will get a bit difficult when you start applying them yourselves. Hopefully after a few days you will start to get the hang of it.</p><p><a href="https://ashok-khanna.medium.com/introduction-to-typescript-part-3-99071f1758c">In Part 3, we will discuss function, object and class typing</a>. Go for a walk and maybe sleep on the above, and come back tomorrow to tackle Part 3!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3c755300d5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to TypeScript]]></title>
            <link>https://ashok-khanna.medium.com/introduction-to-typescript-c3fd1374fd90?source=rss-81f1c825fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3fd1374fd90</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ashok Khanna]]></dc:creator>
            <pubDate>Sat, 28 May 2022 07:53:54 GMT</pubDate>
            <atom:updated>2022-05-30T10:46:28.732Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Four-Part Guide for Experienced JavaScript Developers</h4><p>TypeScript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. It is designed for the development of large applications and transpiles to JavaScript.</p><p>In this article, we provide a succinct introduction to the language, referring readers to <a href="https://www.typescriptlang.org/docs/">official documentation</a> for further reading. Familiarity with modern Javascript (ES2015+) is expected and one can learn more about <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">JavaScript at Mozilla’s Developer Network</a>.</p><h3>Starting off with TypeScript</h3><p>As TypeScript (TS) is a superset of JavaScript (JS), you can begin by using little to none TS in your code and slowly migrate to more of its features. You do need a development environment that transpiles TS to JS, and <a href="https://www.jetbrains.com/webstorm/">JetBrains’ WebSStorm is my personal recommendation</a>, but there are many other fine editors you can use.</p><p>At its core, TypeScript allows you to add <a href="https://en.wikipedia.org/wiki/Type_system"><strong><em>types</em></strong></a> to your code, which allows the TypeScript compiler to <strong><em>statically </em></strong>check typing during compiliation. By this we mean TypeScript checks your code for type errors during compile-time, and not during run-time (that is where dynamic checks are done).</p><p>Annotating your code with types allows the compiler to follow the flow of values through a program and verify that functions and other programming constructs receive and return values of the types annotated to them by the programmer (or inferred by the compiler). A suprising number of bugs are caught by type checking, and as a former non-believer, I now wholeheartedly support static typing checking in JavaScript and code exclusively in TypeScript.</p><h3>Adding Types to JavaScript — Part 1</h3><p>TypeScript has a very natural syntax that will remind you of other statically typed languages. Below are some examples of how to add types to various JavaScript constructs.</p><h4>Primitive Typing</h4><p>The primitive types in TypeScript are string, number and boolean and can be annotated to variables as follows.</p><pre>const text: string;<br>const amount: number;<br>const loggedIn: boolean;</pre><h4>Type Inference</h4><p>Often we do not need to explicitly annotate types and can allow the compiler to infer them:</p><pre>const text = &quot;Hello, World!&quot;;<br>const amount = 1000;<br>const loggedIn = False;</pre><p>Usually a sufficiently capable editor such as WebStorm will provide many typing hints (typically by <a href="https://palantir.github.io/tslint/">leveraging TSLint</a>) that will help you in determining when to add explicit types or rely on the compilers inferred types. For example, if you have a variable that can be either a string or an array of strings, you probably do not want the following type inference:</p><pre>const text = &quot;A&quot; // TypeScript infers text is of type string</pre><p>Rather, you would want to explicitly state the type of the variable as follows.</p><pre>const text: string | Array&lt;string&gt; = &quot;A&quot;</pre><h4>Array &amp; Union Types</h4><p>In the above, we introduced two new concepts. The format for <strong><em>array types</em></strong> is Array&lt;type&gt; where type represents the type of the elements of the array (string in the above example). Secondly, <strong><em>union types</em></strong> are created with |. Another example would be:</p><pre>const primitive: string | number | boolean;</pre><p>In the above example, the variable primitive can be a string, number or a boolean. Now, this is an important point: when using union types, any operation must be valid on every type in that union. For example, the below will be a type error because numbers and booleans do not have a method toUpperCase:</p><pre>console.log(primitive.toUpperCase());      // &lt;-- Type Error</pre><p>To get around this, you would have to do something like:</p><pre>if (typeof primitive === &quot;string&quot;) {<br>  console.log(primitive.toUpperCase());<br>}</pre><p>This example is a small illustration of how type checking prevents bugs in code as it prevents some illegal operations at runtime — without the above <strong><em>type guard</em></strong>, JavaScript would throw an error at runtime if primitive stored a number and we tried calling toUpperCase on it.</p><h4>The ANY Type</h4><p>To round out this section, we note that TypeScript has the any type which effectively lets you bypass all type checking. It usually is not a good idea to use the any type, but you may have to in some instances (but try to avoid it!).</p><pre>let obj: any = { x: 0 };</pre><pre>// None of the following lines of code will throw compiler errors.<br>// Using `any` disables all further type checking, and it is assumed<br>// you know the environment better than TypeScript.</pre><pre>obj.foo();<br>obj();<br>obj.bar = 100;<br>obj = &quot;hello&quot;;<br>const n: number = obj;</pre><h3>Adding Types to JavaScript — Part 2</h3><p>We covered primitive, array and union types so far. We will now introduce other basic concepts and also show you how to create your own types.</p><h4>Adding Types to Functions</h4><p>Below is an example of adding types to a function that accepts three arguments of type number, number and string and returns a value of type number.</p><pre>function add(x: number, y: number, message: string):number {<br>  console.log(message);<br>  return x + y;<br>}</pre><h4>Creating Custom Types</h4><p>We can create our own types with <strong><em>type aliases</em></strong> and <strong><em>interfaces</em></strong>. Both of these do very similar things, with a key distinction that type aliases cannot be re-opened later to add new properties whilst interfaces are always extendable.</p><pre>type Point {<br>  x: number;<br>  y: number;<br>}</pre><pre>interface Point {<br>  x: number;<br>  y: number;<br>}</pre><p>Thus, we can add types to objects as follows:</p><pre>const point: Point</pre><pre>// Equivalent to the below anonymous object type:</pre><pre>const point: { x: number, y: number }</pre><p>We can also create literal types out of strings and numbers, which are particularly useful in unions. They can be combined with non-literal types.</p><pre>type leftAlignment = &quot;left&quot;;   // Only permitted value is &quot;left&quot;</pre><pre>type alignment = leftAlignment | &quot;right&quot; | &quot;center&quot;</pre><pre>type validNum = -1 | 0 | 1</pre><pre>type validInput = Point | validNum | 5    // Refer &#39;Point&#39; def above</pre><h4>Adding Types to Classes</h4><p>The above concepts naturally extend to classes.</p><pre>class PointAdder {<br>  x: number;<br>  y: number;<br>  <br>  constructor(x: number, y: number) {<br>    this.x = x;<br>    this.y = y;<br>  }</pre><pre>  adder(a: number): number {<br>    return this.x + this.y + a;<br>  }</pre><pre>}</pre><p>Note that classes themselves are types:</p><pre>const test: PointAdder;</pre><h3>Next Steps</h3><p>The above was a basic but incomplete introduction to TypeScript. <a href="https://ashok-khanna.medium.com/introduction-to-typescript-part-2-d3c755300d5d">In Part 2, we will expand on how TypeScript actually works and then introduce some more advanced concepts like type guards and type assertions</a>. Grab a coffee and jump back in!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3fd1374fd90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Routing in Plain React]]></title>
            <link>https://ashok-khanna.medium.com/react-routing-in-plain-react-59d87c8384a3?source=rss-81f1c825fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/59d87c8384a3</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ashok Khanna]]></dc:creator>
            <pubDate>Mon, 23 May 2022 10:58:09 GMT</pubDate>
            <atom:updated>2022-05-23T11:12:46.351Z</atom:updated>
            <content:encoded><![CDATA[<h4>React Routing in 50 Lines of Code</h4><p>React Router is one of the most popular React libraries, as it serves as a bridge between React’s SPA philosophy and more traditional multi page websites where links are used for navigation.</p><p>I personally found React Router a bit cumbersome to use. In addition, I generally don’t like having too many dependencies in my project. Fortunately, after searching a bit online, creating my own react router in plain react proved to be relatively straightforward.</p><p>Credits to the following from where I learnt some of the necessary concepts:</p><ul><li><a href="https://chrismorgan.info/about/">https://chrismorgan.info/about/</a></li><li><a href="https://ncoughlin.com/posts/react-navigation-without-react-router/">https://ncoughlin.com/posts/react-navigation-without-react-router/</a></li><li><a href="https://dilshankelsen.com/react-routing-without-react-router/">https://dilshankelsen.com/react-routing-without-react-router/</a></li></ul><p>Without further ado…here is the code :) <a href="https://github.com/ashok-khanna/react-snippets/blob/main/Router.js">Star the repo</a> if you like it (the repo also contains some useful comments and is better formatted than below).</p><pre>import React from &#39;react&#39;;<br>import { useEffect, useState } from &#39;react&#39;;<br><br><strong>window.addEventListener</strong>(&quot;click&quot;, function (event) {<br>    const link = event.target.closest(&quot;a&quot;);<br>    if (<br>        !event.button &amp;&amp;<br>        !event.altKey &amp;&amp;<br>        !event.ctrlKey &amp;&amp;<br>        !event.metaKey &amp;&amp;<br>        !event.shiftKey &amp;&amp;<br>        link &amp;&amp;<br>        link.href.startsWith(window.location.origin + &quot;/&quot;) &amp;&amp;<br>        link.target !== &quot;_blank&quot;<br>    ) {<br>        event.preventDefault();<br>        navigate(link.href);<br>    }<br>});<br><br><strong>export default function Router</strong> ({routes, defaultComponent}) {<br><br>    const [currentPath, setCurrentPath] = useState(window.location.pathname);<br><br>    useEffect(() =&gt; {<br>        const onLocationChange = () =&gt; {<br>            setCurrentPath(window.location.pathname);<br>        }<br><br>        window.addEventListener(&#39;popstate&#39;, onLocationChange);<br><br>        return () =&gt; {<br>            window.removeEventListener(&#39;popstate&#39;, onLocationChange)<br>        };<br>    }, [])<br>    return routes.find(({path, component}) =&gt; path === currentPath)?.component || defaultComponent<br>}<br><br><br><strong>export function navigate </strong>(href)<strong> </strong>{<br><br>    // update url<br>    window.history.pushState({}, &quot;&quot;, href);<br><br>    // communicate to Routes that URL has changed<br>    const navEvent = new PopStateEvent(&#39;popstate&#39;);<br>    window.dispatchEvent(navEvent);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59d87c8384a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Circles with Text in CSS]]></title>
            <link>https://ashok-khanna.medium.com/circles-with-text-in-css-ea1971f693c3?source=rss-81f1c825fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1971f693c3</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ashok Khanna]]></dc:creator>
            <pubDate>Thu, 12 May 2022 10:54:44 GMT</pubDate>
            <atom:updated>2022-05-12T10:54:44.945Z</atom:updated>
            <content:encoded><![CDATA[<h4>Quick Tips in Web Development</h4><p>When designing presentations and websites, I often like to use circles with text contained inside. To achieve this with some basic CSS, we just have to do something like the following.</p><pre>.circle {<br>  background: burlywood;<br>  border: 10px solid #000;<br>  color: #000;</pre><pre>  width: 50vw;<br>  height: 50vw;<br>  font: 8.5vw Arial, sans-serif;<br>  <br>  justify-content: center;<br>  align-items: center;<br>  border-radius: 100%;<br>  text-align: center;<br>  display: flex;<br>}</pre><p>And then something as easy the following in your webpage:</p><pre>&lt;div class=&quot;circle&quot;&gt;Subscribe Now&lt;/div&gt;</pre><p>Try it out! The result should be something similar to the below. Then just play around with the width / height / font size and customise the colors too to your website’s color palette. Enjoy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*EkzuaPt2kIzs6wlkrGWZqQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1971f693c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift and JSON — Introducing the Codable Protocol]]></title>
            <link>https://ashok-khanna.medium.com/swift-and-json-introducing-the-codable-protocol-155121baf445?source=rss-81f1c825fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/155121baf445</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Ashok Khanna]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 09:11:37 GMT</pubDate>
            <atom:updated>2022-04-18T09:11:37.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift and JSON — Introducing the Codable Protocol</h3><h4>Ashok’s Bite Sized Guides — Guide #01</h4><p>JSON has become the lingua franca of data transfer across the World Wide Web. In this bite sized guide, we will introduce <a href="https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types">Swift’s Codable Protocol for encoding and decoding JSON</a>.</p><p>Conforming to the Codable Protocol is straightforward:</p><ul><li>Basic types like STRING, DOUBLE, INT, DATE, DATA or URL automatically conform to Codable</li><li>Any type whose properties are Codable automatically conforms to Codable just by declaring conformance to the protocol:</li></ul><pre>struct Coordinate: Codable {<br>    var latitude: Double<br>    var longitude: Double<br>}</pre><ul><li>Built-in types such as ARRAY, DICTIONARY, and OPTIONAL also conform to Codable whenever they contain codable types</li><li>Indeed, any custom type can also be Codable as long as all of its properties are Codable</li></ul><pre>struct Landmark: Codable {<br>    var name: String<br>    var foundingYear: Int<br>    var location: [Coordinate]<br>}</pre><p>Once we established the Codable protocol for our types, we can readily encode and decode Swift types to JSON.</p><h3>Encoding Swift Objects to JSON</h3><p>Encoding is the easy part. Here is a generic function you can use.</p><pre>func myEncoder&lt;T: Encodable&gt;(_ data: T) throws -&gt; String {</pre><pre>    let encoder = JSONEncoder()</pre><pre>    encoder.keyEncodingStrategy = .convertToSnakeCase</pre><pre>    let jsonData = try encoder.encode(data)</pre><pre>    return String(data: jsonData, encoding: .utf8)!</pre><pre>}</pre><p>Note that Codable is a typealias for the Encodable and Decodable protocols. In the above function, we just need the parameter <strong><em>data</em></strong> to conform to the Encodable protocol (which Codable will also do).</p><h3>Decoding Swift Objects to JSON</h3><p>Decoding objects can be just as easy as encoding, but we also have a few extra options to better handle external data being passed into our programs. <a href="https://www.avanderlee.com/swift/json-parsing-decoding/">Antoine van der Lee covers them well in this post</a>.</p><p>Lets run through some basic concepts first:</p><ul><li>Unless you use custom coding keys (refer to the official <a href="https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types">Apple Documentation</a>), your property names <strong><em>need to match exactly</em></strong> to the keys supplied in the JSON string you are decoding</li><li>This makes sense given Swift would not know how to otherwise guess how to map JSON data to Swift Objects</li><li>As JavaScript is typically written in snake_case whilst Swift is written in camelCase, it is very valuable to set the keyEncodingStrategy and keyDecodingStrategy to .convertToSnakeCase (see above in <strong><em>myEncoder</em></strong>) or .convertFromSnakeCase (see below in <strong><em>myDecoder</em></strong>)</li><li>Any keys in the JSON string that are not defined as properties in your Swift types simply get discarded. This is helpful in that you can update your APIs on the server side without breaking the client code already installed on your users devices (and subsequently requiring an app update to fix).</li></ul><p>With all that said, below is an example of a decoder function — it is not too scary! [Actually it does some nice things with protocols and generics, but that’s not related to decoding JSON :)]</p><pre>func myDecoder&lt;T: Decodable&gt;(_ decodeType: T.Type, _ from: String) throws -&gt; T {</pre><pre>   let decoder = JSONDecoder()</pre><pre>   decoder.keyDecodingStrategy = .convertFromSnakeCase</pre><pre>   let jsonData = from.data(using: .utf8)!</pre><pre>   return try decoder.decode(decodeType, from: jsonData)</pre><pre>}</pre><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=155121baf445" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Covid Stole Our Time and How We Can Get It Back [Repost]]]></title>
            <link>https://ashok-khanna.medium.com/how-covid-stole-our-time-and-how-we-can-get-it-back-repost-7fbd894a40bc?source=rss-81f1c825fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fbd894a40bc</guid>
            <dc:creator><![CDATA[Ashok Khanna]]></dc:creator>
            <pubDate>Sat, 26 Feb 2022 06:19:35 GMT</pubDate>
            <atom:updated>2022-02-26T06:19:35.030Z</atom:updated>
            <content:encoded><![CDATA[<h4>By Tim Urban</h4><p>Mr. Urban is the author of <a href="https://waitbutwhy.com/">Wait but Why</a>, a stick-figure-illustrated blog about almost everything. He first wrote about the idea of “<a href="https://waitbutwhy.com/2015/12/the-tail-end.html">Depressing Math</a>” in 2015.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*VI09M6q-PSTpqjXR" /></figure><p>I have good news and bad news for you. Let’s start with the bad: a concept I call Depressing Math.</p><p>Check this out:</p><p>That’s one box for every week of a 90-year life. It often feels like we have countless weeks ahead of us. But actually, it’s just a few thousand — a small-enough number to fit neatly in a single image.</p><p>Once you visualize the human life span, it becomes clear that so many parts of life we think of as “countless” are in fact quite countable.</p><p>I love going to the American Museum of Natural History, and I’ve been three times since I moved to New York in 2009. If that rate continues, I’ll step into the museum 12 more times. For an activity I think of as “something I like to do,” that number seems shockingly low. I also love going to the movies, but ever since it became effortless to stream everything at home, I’ve been averaging one or two movie theater trips a year. In my head, I’ll go out for hundreds more movies in my life, but the real amount is probably some weirdly small number like 53.</p><p>Depressing Math is especially depressing when you’re living through a pandemic. Covid hasn’t taken away our weeks, but it has robbed us of our favorite activities — experiences that are already in short supply.</p><p>But perhaps the hardest math to process — and, in turn, the hardest Covid pill to swallow — has to do with our relationships. I grew up spending some time with my parents almost every day. Since turning 19 and moving away for good, I’ve averaged about 10 to 15 days a year with them. If I’m one of the lucky ones, I’ll have quality time with my parents until I’m 60. That means that the day I headed off to college, I had something like 350 remaining parent days <em>total </em>— the amount of time I had with them <em>every year</em> of my childhood.</p><p>What it boils down to is this: My life, in the best-case scenario, will consist of around 20 years of in-person parent time. The first 19 happened over the course of my first 19 years. The final year is spread out over the rest of my life. When I left for college, I had many decades left with living parents, but only about one year of time left to spend <em>with</em> them.</p><p>It’s the same story with childhood friends. I spent high school sitting around with the same four friends, notching somewhere around 1,000 hangouts by the time we scattered off to different cities. Since then, our text thread keeps us in touch, but we’ve only managed to get the whole group together for a weekend every few years — about 10 total days each decade. It feels like we’re smack in the middle of our lives together, but like me and my parents, the high school group is currently enjoying its final 5 percent of in-person time together.</p><p>Depressing Math reveals a cold truth: While you may not be anywhere near the end of your life, you may very well be nearing the end of your time spent with some of the most important people in your life.</p><p>The pandemic has only added to the sting. In my family, Thanksgiving is the ultimate unskippable event, but over the past two years, we’ve skipped it twice because of Covid. Considering that there may only be 10 or 15 more Thanksgivings for us to be all together, two is a pretty big piece of that pie.</p><p>In the months ahead, as you prepare to make plans — or to cancel them — I encourage you to do some Depressing Math of your own. Because whatever your situation, delusion about the time we have left serves no one.</p><p>Now for the good news:</p><p>We think a lot about those black lines: the roads not taken, the opportunities missed, the ones that got away. But most of us greatly underestimate the size of the lush green tree of possibilities that lie ahead of us.</p><p>We underestimate future possibilities for the same reason we overestimate the time we have left with those we love: our intuition is not very imaginative. It’s a human instinct to believe the life we’re used to is how things will always be, both the good parts and the bad.</p><p>Wallowing in regret carries an implicit assumption that we had agency in the past — that we could have <em>had</em> those other life paths if only we had made better decisions. When we think about the future, though, that feeling of agency often disappears, which can leave us feeling resigned and even hopeless.</p><p>But the life we’ll be living 10 years from now will largely be determined not by our past selves but by our present and future selves. If we imagine what we might regret down the road, it’s very much in our hands to do something about it now.</p><p>This is the good news about being a human. The time we have left with family and friends is not a law of nature like the weeks we have left to live. It’s a function of priorities and decisions.</p><p>At our current pace of 10 to 15 days per year, my parents and I have at best a couple of hundred days left to hang out. But there’s nothing stopping us from changing that equation. Agreeing upon an additional annual family week each summer would almost double our remaining time together, while moving to the same city could multiply it by 10. Getting together with my friends one weekend a year would triple our pace and leave us with 15 percent of our total hangout time ahead, instead of just 5 percent. If the thought of only 12 more Museum of Natural History visits makes me sad, I can start going once a year and magically transform that number to 50. That big green tree is a reminder that we have the power to change so much of what seems set in stone.</p><p>These two delusions — that we have countless time ahead of us and that we can’t change our course — are a recipe for complacency. Shedding them can wake us up and inspire us to live more wisely. The past couple of years has left us with a joy deficit. When we picture a post-Covid world, we imagine having our old lives back. But we can actually go a step further and make up for the missed experiences, flipping the deficit into a surplus. If Covid has given us anything, it’s a rare chance for a reset. Let’s take it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fbd894a40bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Presentation Types in CLIM]]></title>
            <link>https://ashok-khanna.medium.com/presentation-types-in-clim-b1dc5ced433e?source=rss-81f1c825fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1dc5ced433e</guid>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[common-lisp]]></category>
            <dc:creator><![CDATA[Ashok Khanna]]></dc:creator>
            <pubDate>Thu, 24 Feb 2022 11:22:15 GMT</pubDate>
            <atom:updated>2022-02-24T11:22:15.944Z</atom:updated>
            <content:encoded><![CDATA[<h4>Abridged Notes Chapter 8 of Franz CLIM User Guide</h4><p>The below are abridged, very lightly modified, notes from Chapter 8 Presentation Types in <a href="https://franz.com/support/documentation/10.1/doc/clim-ug.pdf">Franz’s CLIM 2.2 User Guide</a>. All credit and copyright belong to Franz and their documentation represents an <strong><em>excellent</em></strong> example of technical writing, for which I’m highly grateful for.</p><p>In object-oriented programming systems, applications are built around internal objects that model something in the real world. For example, an application that models a university has objects representing students, professors, and courses.</p><p>Users need to interact with the application objects. In most user interface systems, the interface is constructed in terms of the objects in the UI toolkit; these objects must be converted, by the programmer, into the objects of the application. For example, choosing one of a set of objects might require you to build a radio box that has in it a set of buttons. Each of these buttons stands for one of the objects being chosen among. You must also write code that converts each of these buttons back into an application object, so that when the end-user picks on of the buttons, the correct application object is chosen.</p><p>If you later decide that the radio box is too cumbersome (perhaps because there are many selections in it), and you wish to change the user interface to use a list pane or option pane, you must then rewrite all of this code to use the new toolkit objects for list or option panes.</p><p>A CLIM user interface enables users to see a visual representation of the application objects, and to operate on them. The objects that appear on the screen are not the application objects themselves; they are objects called presentations that are one step removed. The visual representation of an object is a stand-in for the application object itself, in the same sense that the word ‘cat’ (or a picture of a cat) is a stand-in for a real cat.</p><p>In CLIM, the user interface is constructed is terms of the application objects, and CLIM worries about the toolkit objects. Taking the same example, all you need to do is to specify that you wish to select one of the application objects by using the member type. CLIM deduces that this can be done via a radio box, and creates the radio box for you. If you later decide to use a list pane or option pane, you can advise CLIM to do this by explicitly specifying a <em>view</em>. At no time do you need to worry about the toolkit objects.</p><p>The most basic part of designing a CLIM user interface is to specify how users will interact with the application objects. There are two directions of interaction: you must present application objects to the user as output, and you must accept input from the user that indicates operations on the application objects. This is done with two basic functions, <strong>present </strong>and <strong>accept</strong>, and some related functions.</p><h4><strong>8.1.1 Presentations</strong></h4><p>CLIM keeps track of the association between a visual representation of an object and the object itself. CLIM maintains this association in a data structure called a <strong><em>presentation</em></strong>. A presentation embodies three things:</p><ul><li>The underlying application object</li><li>Its presentation type</li><li>Its visual representation</li></ul><h4><strong>8.1.2 Output with its semantics attached</strong></h4><p>For example, a university application has a ‘student’ application object. The user sees a visual representa- tion of a student, which might be a textual representation, or a graphical representation (such as a form with name, address, student id number), or even an image of the face of the student. The presentation type of the student is ‘student’; that is, the semantic type of the object that appears on the screen is ‘student’. Since the type of a displayed object is known, CLIM knows which operations are appropriate to perform on the dis- played object, <em>irrespective </em>of what visual representation is being used for the object. For example, when a student is displayed, it is possible to perform operations such as ‘send tuition bill’ or ‘show transcript’.</p><h4><strong>8.1.3 Input context</strong></h4><p>Presentations are the basis of many of the higher-level application-building tools, which use <strong>accept </strong>to get input and <strong>present </strong>to do output. A command that takes arguments as input states the presentation type of each argument.</p><p>This sets up an <strong><em>input context</em></strong>, in which presentations of that type are sensitive (they are highlighted when the pointer passes over them). When the user gives the ‘send tuition bill’ command, the input context is looking for a student, so any displayed students are sensitive. Presentations that have been output in previous user interactions retain their semantics. In other words, CLIM has recorded the fact that a student has been displayed, and has saved this information so that whenever the input context expects a stu- dent, all displayed students are sensitive.</p><h4><strong>8.1.4 Inheritance</strong></h4><p>CLIM presentation types can be designed to use inheritance, just as CLOS classes do. For example, a university might need to model night student, which is a subclass of student. When the input context is looking for a student, night students are sensitive because they are represented as a subtype of student.</p><h4><strong>8.1.5 Presentation translators</strong></h4><p>You can define <em>presentation translators </em>to make the user interface of your application more flexible. For example, suppose the input context is expecting a command. Since CLIM commands are first class appli- cation objects, in this input context, all displayed commands are sensitive, so the user can point to one to execute it. However, suppose the user points to another kind of displayed object, such as a student. In the absence of a presentation translator, the student is not sensitive because the user must enter a command and cannot enter anything else to this input context.</p><p>In the presence of a presentation translator that translates from students to commands, however, the stu- dent would be sensitive. In one scenario, the student is highlighted, and the middle pointer button does ‘show transcript’ of the student.</p><h4><strong>8.1.6 What the application programmer does</strong></h4><p>By the time you get to the point of designing the user interface, you have probably designed the rest of the application and know what the application objects are. At this point, you need to do the following:</p><ul><li>First decide which types of application objects will be presented to the user as output and accepted from the user as input. For each type of application object that the user will see, assign a corresponding presentation type. You will need to define <strong>accept </strong>and <strong>present </strong>methods for these objects, unless these methods can be inherited from a superclass. In many cases, this means simply using a predefined presentation type. In other cases, you need to define a new presentation type. Usually the presentation type is the same as the class of the application object.</li><li>Decide which of the application’s operations should be available from the user interface, and define commands for each of these operations. These commands can be made available from a variety of interfaces (such as menus or dialogs, command lines, and so on). This is a detail that can be decided as you continue to develop the program.</li><li>Use the application-building tools to specify the windows, menus, commands, and other elements of the user interface. Most of these elements will use the presentation types of your objects.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1dc5ced433e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criteria of Object Orientation]]></title>
            <link>https://ashok-khanna.medium.com/criteria-of-object-orientation-1fe0f81ac767?source=rss-81f1c825fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fe0f81ac767</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ashok Khanna]]></dc:creator>
            <pubDate>Sun, 09 Jan 2022 07:33:39 GMT</pubDate>
            <atom:updated>2022-01-09T07:33:39.436Z</atom:updated>
            <content:encoded><![CDATA[<h4>Notes from Chapter 2, Object Oriented Software Construction By Bertrand Meyer</h4><p><strong><em>All credits for the below to </em></strong><a href="https://bertrandmeyer.com/"><strong><em>Bertrand Meyer</em></strong></a><strong><em>, this is just my personal notes, which are 90%+ copied word by word from his textbook Object Oriented Software Construction.</em></strong></p><p>This article will provide a concise listing of the criteria that makes a system object-oriented. We group the criteria into three sections — method and language, implementation and environment, and libraries.</p><h3>Method and Language</h3><h4>Seamlessness</h4><p>An object-oriented language and environment, together with the supporting method, should apply to the entire lifecycle, in a way that minimises the gaps between successive activities.</p><h4>Classes</h4><p>The method and language should have the notion of class as their central concept. Informally, a class is a software element describing an abstract data type and its partial or total implementation. An abstract data type is a set of objects defined by the list of operations, or <em>features</em>, applicable to these objects, and the properties of these operations.</p><h4>Assertions</h4><p>The language should make it possible to equip a class and its features with assertions (preconditions, postconditions and invariants), relying on tools to produce documentation out of these assertions and, optionally, monitor them at run time.</p><h4>Classes as Modules</h4><p>In a pure object-oriented approach, classes should be the only modules such that there is no notion of main program, and subprograms do not exist as independent module units, but rather appear as part of classses.</p><h4>Classes as Types</h4><p>The notion of class is powerful enough to avoid the need for any other typing mechanism. Every type should be based on a class.</p><h4>Feature-based Computation</h4><p>In object-oriented computation, there is only one basic computational mechanism: given a certain object, which (because of the previous rule) is always an instance of some class, call a feature of that class on that object.</p><h4>Information Hiding</h4><p>It should be possible for the author of a class to specify that a feature is available to all clients, to no client, or to specified clients. An immediate consequence of this rule is that communication between classes should be strictly limited. In particular, a good object-oriented language should not offer any notion of global variable; classes will exchange information exclusively through feature calls, and through the inheritance mechanism.</p><h4>Exception Handling</h4><p>The language should provide a mechanism to recover from unexpected abnormal situations.</p><h4>Static Typing</h4><p>A well-defined type system should, by enforcing a number of type declaration and compatibility rule, guarantee the run-time type safety of the systems it accepts. This requires every entity is explicitly declared as being of a certain type, derived from a class. Assignment and argument passing are subject to conformance rules, based on inheritance, which require the source’s type to be compatible with the target’s type.</p><h4>Genericity</h4><p>For typing to be practical, it must be possible to define type-parameterized classes, known as generic. A generic class <em>LIST </em>[<em>G</em>] will describe lists of elements of an arbitrary type represented by <em>G</em>, the “formal generic parameter”; you may then declare specific lists through such derivations as <em>LIST </em>[<em>INTEGER</em>] and <em>LIST </em>[<em>WINDOW</em>], using types <em>INTEGER </em>and <em>WINDOW </em>as “actual generic parameters”. All derivations share the same class text.</p><h4>Inheritance</h4><p>It should be possible to define a class as inheriting from another. It should be possible for a class to inherit from as many others as necessary, with an adequate mechanism for disambiguating name clashes.</p><h4>Constrained Genericity</h4><p>The combination of genericity and inheritance brings about an important technique, constrained genericity, through which you can specify a class with a generic parameter that represents not an arbitrary type as with the earlier (unconstrained) form of genericity, but a type that is a descendant of a given class.</p><p>A generic class <em>SORTABLE_LIST</em>, describing lists with a <em>sort </em>feature that will reorder them sequentially according to a certain order relation, needs a generic parameter representing the list elements’ type. That type is not arbitrary: it must support an order relation. To state that any actual generic parameter must be a descendant of the library class <em>COMP ARABLE</em>, describing objects equipped with an order relation, use constrained genericity to declare the class as <em>SORTABLE_LIST </em>[<em>G –</em>&gt; <em>COMPARABLE</em>].</p><p>The genericity mechanism should support the constrained form of genericity.</p><h4>Redefinition</h4><p>It should be possible to redefine the specification, signature and implementation of an inherited feature. Redefinition may affect the implementation of a feature, its signature (type of arguments and result), and its specification.</p><h4>Polymorphism</h4><p>In programming languages and type theory, <strong>polymorphism</strong> is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types. It should be possible to attach entities (names in the software texts representing run-time objects) to run-time objects of various possible types, under the control of the inheritance-based type system.</p><h4>Dynamic Binding</h4><p>Calling a feature on an entity should always trigger the feature corresponding to the type of the attached run-time object, which is not necessarily the same in different executions of the call. Dynamic binding has a major influence on the structure of object-oriented applications, as it enables developers to write simple calls (meaning, for example, “call feature turn on entity my_boat”) to denote what is actually several possible calls depending on the corresponding run-time situations. This avoids the need for many of the repeated tests (“Is this a merchant ship? Is this a sports boat?”) which plague software written with more conventional approaches.</p><blockquote>Object-oriented software developers soon develop a healthy hatred for any style of computation based on explicit choices between various types for an object. Polymorphism and dynamic binding provide a much preferable alternative.</blockquote><h4>Run-time Type Interrogation</h4><p>In some cases, an object comes from the outside, so that the software author has no way to predict its type with certainty. This occurs in particular if the object is retrieved from external storage, received from a network transmission or passed by some other system. It should be possible to determine at run time whether the type of an object conforms to a statically given type.</p><h4>Deferred Features and Classes [Note — Is this equivalent to the concept of Protocols?]</h4><p>In some cases for which dynamic binding provides an elegant solution, obviating the need for explicit tests, there is no initial version of a feature to be redefined. For example class BOAT may be too general to provide a default implementation of turn. Yet we want to be able to call feature turn to an entity declared of type BOAT if we have ensured that at run time it will actually be attached to objects of such fully defined types as MERCHANT-SHIP and SPORTS_BOAT.</p><p>In such cases BOAT may be declared as a deferred class (one which is not fully implemented), and with a deferred feature turn. Deferred features and classes may still possess assertions describing their abstract properties, but their implementation is postponed to descendant classes. A non-deferred class is said to be effective. It should be possible to write a class or a feature as deferred, that is to say specified but not fully implemented.</p><h4>Memory Management and Garbage Collection</h4><p>The language should make safe automatic memory management possible, and the implementation should provide an automatic memory manager taking care of garbage collection.</p><h3>Implementation and Environment</h3><h4>Automatic Update</h4><p>Software development is an incremental process. Developers do not commonly write thousands of lines at a time; they proceed by addition and modification, starting most of the time from a system that is already of substantial size.</p><p>For example, if you change a feature <em>f </em>of class <em>C</em>, you must be certain that every descendant of <em>C </em>which does not redefine <em>f </em>will be updated to have the new version of <em>f</em>, and that every call to <em>f </em>in a client of <em>C </em>or of a descendant of <em>C </em>will trigger the new version. System updating after a change should be automatic, the analysis of inter- class dependencies being performed by tools, not manually by developers.</p><h4>Fast Update</h4><p>The time to process a set of changes to a system, enabling execution of the updated version, should be a function of the size of the changed components, independent of the size of the system as a whole. In the case of compiled languages, this requires the compiler to be incremental.</p><h4>Persistence</h4><p>An object will often contain references to other objects; since the same may be true of these objects, this means that every object may have a large number of <strong>dependent</strong><em> </em>objects, with a possibly complex dependency graph (which may involve cycles). It would usually make no sense to store or retrieve the object without all its direct and indirect dependents. A persistence mechanism which can automatically store an object’s dependents along with the object is said to support <strong>persistence closure</strong>.</p><p>A persistent storage mechanism supporting persistence closure should be available to store an object and all its dependents into external devices, and to retrieve them in the same or another session.</p><p>For some applications, mere persistence support is not sufficient; such applications will need full <strong>database support</strong>. The notion of object-oriented database is covered in a later chapter in Bertrand Meyer’s book, which also explores other persistent issues such as <strong>schema evolution</strong>, the ability to retrieve objects safely even if the corresponding classes have changed.</p><h4>Documentation</h4><p>Automatic tools should be available to produce documentation about classes and systems. Assertions, as already noted, help make such software-extracted documents precise and informative.</p><h4>Browsing</h4><p>Interactive browsing facilities should enable software developers to follow up quickly and conveniently the dependencies between classes and features.</p><h3>Libraries</h3><p>An object-oriented environment should provide good libraries, and mechanisms to write more.</p><h4>Basic Libraries</h4><p>An object-oriented development environment must provide reusable classes addressing these common needs of software systems. Reusable classes should be available to cover the most frequently needed data structures and algorithms.</p><h4>Graphical User Interfaces</h4><p>Reusable classes should be available for developing applications which provide their users with pleasant graphical user interface.</p><h4>Library Evolution Mechanisms</h4><p>Mechanisms should be available to facilitate library evolution with minimal disruption of client software.</p><h4>Library Indexing Mechanisms</h4><p>Another problem raised by libraries is the need for mechanisms to identify the classes addressing a certain need. This criterion affects all three categories: libraries, language (as there must be a way to enter indexing information within the text of each class) and tools (to process queries for classes satisfying certain conditions). Library classes should be equipped with indexing information allowing property-based retrieval.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fe0f81ac767" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>