Skip to main content

TypeScript Generic Function Reported As JSX Error

· 3 min read

Motivation

const genericFn = <T>() => {
return "This is a poorly written example generic function"
}

Above is an example of a function with a generic parameter T that could potentially be used within the function body. However, if the above code is saved in a .tsx file (In my context, within a React application, while trying to create a generic custom hook), you will receive with the following error when hover over <T>:

JSX element 'T' has no corresponding closing tag.ts(17008)
Cannot find name 'T'.ts(2304)

Exploration

Defining generic function in TypeScript

To resolve the issue, I started with researching on how to properly define a generic function in TypeScript. Perhaps I made a mistake somewhere in the above syntax. I landed on two articles here and here. Both of them talked about how to create a custom React hook that uses generics. However, the syntax used in the articles were similar to the above example but no errors were discussed.

While I did not find an answer after heading over to TypeScript-CheatSheets, I thought the note on avoiding type inference when declaring custom hook was an interesting point that I did not know about.

If you are returning an array in your Custom Hook, you will want to avoid type inference as TypeScript will infer a union type (when you actually want different types in each position of the array). Instead, use TS 3.4 const assertions:

export function useLoading() {
const [isLoading, setState] = React.useState(false);
const load = (aPromise: Promise<any>) => {
setState(true);
return aPromise.finally(() => setState(false));
};
return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[]
}

This way, when you destructure you actually get the right types based on destructure position.

Credit: TypeScript-CheatSheets


Google the error

Moving on with the second strategy: "Google & Stack overflow". Searching the above error landed me on the following issue in the Microsoft TypeScript repository. There were a few more interesting links here and here.

So according to the reported issue:

The usage of <T> prior to the function braces causes a JSX error within .tsx files: "JSX element has no corresponding closing tag.". Basic example works as expected in a .ts file.

The issue was claimed to be a limitation and there were a few workarounds mentioned (in the thread and also in the related stack overflow post):

  • change from .tsx to .ts
  • add a comma: const f = <T,>(arg: T): T => {...}
  • extend this way: const foo = <T extends unknown>(x: T) => x;
  • or extend this way: const foo = <T extends {}>(x: T): T => x;

Thoughts

Funny how issues like this one will continue to bite us even way into the future... simply because no one is going to do anything about it?

Exploring [key:string]: any in TypeScript

· 4 min read

With this series I intend to note down some of the confusion and quirky stuff that I encountered out in the wild. So, today I am going to start with this snippet in TypeScript.

Motivation

interface CustomState {
value: {
[key:string]: any
}
}

const defaultState : CustomState = {
value: {}
}

const reducer = (state: CustomState, action: { type: string }): CustomState => {
if (action.type === 'reset') {
return {
value: []
}
} else {
return {
...state
}
}
}

The CustomState declared at the start includes a property called value, which is an object with key-value pairs of the form string - any. The defaultState variable contains an (empty) object conforming to the interface declared above, which is perfectly normal.

The thing that caught me off-guard is in the reducer. The reducer function is supposed to reset the state by clearing out the value property. However, notice here that an array [] is used, instead of {}.

I thought the change from type object to type array is pretty drastic, especially if I compare it to Java (Changing from a HashMap to an ArrayList just like that? Is this even allowed?). The strangest part of this was that TypeScript had no qualms about this at all. No curly lines nor compiler warnings.


Exploration

The first thing I did was to find out whether the interface was declared correctly, i.e. is it declaring that value contains an object or an array. This led me to review the definition of index signature.

Index Signature

Index signature is a way to describe the types of possible values. Borrowing the examples used in the official TypeScript docs:

interface StringArray {
[index: number]: string;
}

const myArray: StringArray = getStringArray();
const secondItem = myArray[1]; // secondItem is of type string

The syntax to declare the index signature might seem strange at first. It looks like declaring an object with {} but in the above example, it is used for declaring an interface for an array. For comparison, the way to declare an object interface looks like this:

interface PaintOptions {
xPos: number;
yPos: number;
}

In the TypeScript documentation example, index signature is used to describe an array. However, there is also a line below that says:

While string index signatures are a powerful way to describe the “dictionary” pattern, they also enforce that all properties match their return type.

Doing a bit more research would point me to other examples of how index signatures are also applicable to objects:

interface NumberDictionary {
[index: string]: number;
length: number;
width: number;
}

So in the case of CustomState, both the following usage are correct:

const arrayExample:CustomState = {
value: [{val: 1}]
}

const objectExample:CustomState = {
value: {val: 1}
}

Array VS Object

The second thing I checked was that since {} could be replaced with [], are arrays and objects, besides what we already know about the different use cases, the same thing in JavaScript/TypeScript? Without going too deep into this question, we can make an observation with console log :

console.log(typeof []) // "object"
console.log(typeof {}) // "object"

Stack Overflow?

The last bit of things of interest came up when I started to draft examples for this article and encountered this stack overflow question. Essentially, the person had an issue with Index signature of object type implicitly has an 'any' type. Scrolling further down, an proposed answer had something similar to my initial example:

type ISomeType = {[key: string]: any};

let someObject: ISomeType = {
firstKey: 'firstValue',
secondKey: 'secondValue',
thirdKey: 'thirdValue'
};

let key: string = 'secondKey';

let secondValue: string = someObject[key];

In fact to add on, the declaration of ISomeType allows for the following to work as well:

type ISomeType = {[key: string]: any};

// My additional example
let someArray: ISomeType = [
{firstKey: 'firstValue'},
{secondKey: 'secondValue'},
{thirdKey: 'thirdValue'}
]

let newkey: string = 'secondKey';

let newSecondValue: string = someArray[newkey];

But, if the use of any has been replaced, the whole thing would break:

// Note the change in the type and therefore the error!
type ISomeTypeA = {[key: string]: string};

let someObjectA: ISomeTypeA = {
firstKey: 'firstValue',
secondKey: 'secondValue',
thirdKey: 'thirdValue'
};

let keyA: string = 'secondKey';

let secondValueA: string = someObjectA[keyA];

// My additional example
let someArrayA: ISomeTypeA = [ // Error: Type '{ firstKey: string; }' is not
{firstKey: 'firstValue'}, // assignable to type 'string'.
{secondKey: 'secondValue'},
{thirdKey: 'thirdValue'}
]

let newkeyA: string = 'secondKey';

let newSecondValueA: string = someArrayA[newkeyA];

Potential moral of the story? Don't use any 😂


Resources

The code snippets used in this article is also available at this TypeScript playground.

Learn To Recognize Code Smell

· 3 min read

“Smells,” you say, “and that is supposed to be better than vague aesthetics?” Well, yes. We have looked at lots of code, written for projects that span the gamut from wildly successful to nearly dead. In doing so, we have learned to look for certain structures in the code that suggest—sometimes, scream for—the possibility of refactoring.

  • Kent Beck and Martin Fowler, Refactoring

Code smell is a term used to describe the tell-tail signs of bad software and therefore an indication that refactoring is overdue. Similar to design patterns that we learn to recognize and apply in our software, naming and identifying different code smells can help us triage the existing code base and proceed to apply fixes in the form of refactoring.

Below is a catalog of code smells identified by Martin Fowler

  • Alternative Classes with Different Interfaces
  • Comments
  • Data Class
  • Data Clumps
  • Divergent Change
  • Duplicated Code
  • Feature Envy
  • Global Data
  • Insider Trading
  • Large Class
  • Lazy Element
  • Long Function
  • Long Parameter List
  • Loops
  • Message Chains
  • Middle Man
  • Mutable Data
  • Mysterious Name
  • Primitive Obsession
  • Refused Bequest
  • Repeated Switches
  • Shotgun Surgery
  • Speculative Generality
  • Temporary Field

A Practical Example: Comments

Comments are helpful when used to make clarifications and explain the purpose of the code. However, comments are also tricky to write because when done poorly, they can be a source of noise and potentially exposed the weakness in software. On top of the techniques of writing good comments, let's take a look at how comments can become code smells that prompt us to refactor.

Comments that describe what a function does

// add expenditure to record
void processInput(int data) {
//...
}

Course of action: Rename function and remove comment

void recordExpenditure(int amount) {
//...
}

Comments that describe what a block of code does

static Command parseInput(String input) throws InvalidInputException {
String task = Parser.tokenize(input)[0];
// check if the user input contains recognized keywords
boolean hasKeyword = Arrays
.stream(TaskType.values())
.map(TaskType::getRep)
.anyMatch(x -> x.equals(task));
if (!hasKeyword) {
return false;
}
return Parser.interpret(input);
}

Course of action: Extract function

private static boolean hasTaskKeyword(String input) {
String task = Parser.tokenize(input)[0];
return Arrays
.stream(TaskType.values())
.map(TaskType::getRep)
.anyMatch(x -> x.equals(task));
}

static Command parseInput(String input) throws InvalidInputException {
if (!hasTaskKeyword(input)) {
throw new InvalidInputException(input);
}
return Parser.interpret(input);
}

Comments that describe assumptions

public ShowCommand(Index index) {
// note that index must not be null!
// and index must be larger or equal to zero!
this.index = index;
}

Course of action: Be defensive & use assertions

public ShowCommand(Index index) {
requireNonNull(index);
assert index.getZeroBased() >= 0;
this.index = index;
}

Further reading