DEV Community

Denys
Denys

Posted on • Updated on

TS is a liar

Motivation

Sometimes I hear from people such an amazing opinion about typescript and the reliability of this. My motivation is to clarify some cases, cuz our best language is becoming modern every day and we use some things that we couldn't use a couple of years ago.

Prerequisites

  • typescript

Cases

First and my favorite is ts and Map:

const map = new Map<string,string>()

map.set('tsIsAmazing','thinkNot')

// some
// a lot of
// code
// here

const data = {...map}

data.set('isItWillWork','NOPE')
Enter fullscreen mode Exit fullscreen mode

In this case, we have no errors from the typescript in the last line, but if we run this code it will bring an exception like: data.set is not a function. Be careful

Second:

const merge = <T, F>(source: T, target: F) => ({...source, ...target});

const str = {func: () => '42'};
const num = {func: () => 42};
const fn = {func: () => Function};

const merged = merge(str, merge(num, fn)).func()
console.log(merged);
Enter fullscreen mode Exit fullscreen mode

You can guess what will me in the last console.log, but, sadly it will be a string (as typescript guessing), but in the runtime, it will be Function.

Third

const test = NaN as const
Enter fullscreen mode Exit fullscreen mode

It will throw an ts exception like: A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.(1355), but from the typescript: var NaN: number.

Fourth

class Person{
  age: number
  constructor(age:number){
    this.age = age
  }

  getAge(){
    return this.age
  }
}

const {getAge} = new Person(18)

getAge()
Enter fullscreen mode Exit fullscreen mode

Looks like normal code, but in this case, we will have an error from the getAge invocation like: Cannot read properties of undefined (reading 'age')

Outro

There are a lot of cases like this and a lot of issues in ts repo, this is only 4th and I can write more and more but it's not my point. My point is to keep in touch with ourselves that typescript is not safe and not reliable in some cases.

Top comments (0)