最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there any way to make JS strongly typed? - Stack Overflow

programmeradmin0浏览0评论

JavaScript is a weakly dynamically typed language. I don't mind the dynamic typing, but the weak typing means lots of frustration at unexpected type coercion when I least expect it. Lots of articles online claim to solve this issue but they all confuse weak typing with dynamic typing, and propose solutions such as TypeScript. I would like something more similar to Python's type behaviours - dynamically typed variables but no implicit type coercion. Is there a language or library that does this?

JavaScript is a weakly dynamically typed language. I don't mind the dynamic typing, but the weak typing means lots of frustration at unexpected type coercion when I least expect it. Lots of articles online claim to solve this issue but they all confuse weak typing with dynamic typing, and propose solutions such as TypeScript. I would like something more similar to Python's type behaviours - dynamically typed variables but no implicit type coercion. Is there a language or library that does this?

Share Improve this question asked Mar 7, 2021 at 13:04 EnderShadow8EnderShadow8 1,0501 gold badge8 silver badges23 bronze badges 1
  • Maybe one day: github./tc39/proposal-type-annotations – Flavien Volken Commented Jun 30, 2023 at 12:33
Add a ment  | 

1 Answer 1

Reset to default 9

No it isn't, and it is the reason why typescript was built.
Your question is also kind of a duplicate of this. Have a look, you may find some answers ;)

That said, you could use a good IDE, even visual studio code try to help with their Javscript type checking, worth have a look.

Here a small implementation example

//@ts-check

export class Dog {
  /**
  * @param {string} name
  * @param {number} age
  */
  constructor(name, age) {
    super()
    this.name = name
    this.age = age
  }

  speak () {
    console.log(`${this.name}: No! No more talk!`)
  }
}

new Dog(7, 'Wez').speak() // <-- You should get an error here, it should be Dog('wez', 7)

Edit
If you really wants to have a strong type language for the web, you may :

  • Use webassembly to bring your python code into the browser -> https://github./wasmerio/wasmer-python
  • Give a look at the typescene framework which claim to be a robust Web app framework made with TypeScript: strongly typed, but I never tested it to be honest.
发布评论

评论列表(0)

  1. 暂无评论