简体   繁体   English

TypeScript中的“:”是什么意思?

[英]What's the meaning of “:” in TypeScript?

I'm knew to typescript/javascript but have experience with python/java/c++.我知道打字稿/javascript,但有使用 python/java/c++ 的经验。 Is this like the type hints in the newer versions of Python?这是否像 Python 较新版本中的类型提示? Does ":" always mean a type hint or can it also mean something else? “:”是否总是意味着类型提示或者它也可以意味着其他东西?

TypeScript is a superset of ECMAScript, so first of all, the colon : has all the same meanings it has in ECMAScript: TypeScript 是 ECMAScript 的超集,所以首先,冒号:在 ECMAScript 中具有相同的含义:

  • It is part of the syntax for the conditional operator condition? consequence1: consequence2它是条件运算符condition? consequence1: consequence2 condition? consequence1: consequence2 which evaluates the condition and depending on its truthiness evaluates either consequence1 or consequence2 (but never both), and the value of the whole expression is the value of the consequence that was evaluated. condition? consequence1: consequence2 2 评估condition并根据其真实性评估consequence1 1 或consequence2 2(但绝不会同时评估结果),整个表达式的值是被评估的结果的值。
  • It is part of the syntax for an object literal :它是object 文字语法的一部分:
     const obj = { foo: 4, "bar": 8, ["ba" + "z"]: 15, } console.log(obj);
  • It is an assignment property , part of the syntax for destructuring assignment :它是一个赋值属性,是解构赋值语法的一部分:
     const obj = { foo: 16, bar: 23, baz: 42, } const { foo: frotz, baz: quux } = obj; console.log(frotz, quux);
  • It is part of the syntax for a label :它是label语法的一部分:
     someLabel: for (let i = 0; i < 2; i++) { for (let j = 100; j < 102; j++) { console.log({ i, j }); continue someLabel; } }

But it also has additional meaning in TypeScript, where it is used for type annotations :但它在 TypeScript 中也有其他含义,用于类型注释

const i: number = 4711;
const s: string = "Hello";

function f(a: number, b: string): never

Note that these are not "type hints".请注意,这些不是“类型提示”。 They are type annotations .它们是类型注释 They aren't hinting at anything, they are strictly enforced.他们没有暗示任何事情,他们被严格执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM