From ae194af8d7f4294bd03d96e73f14ed9deaa44154 Mon Sep 17 00:00:00 2001 From: yanyilin Date: Fri, 14 Jun 2024 20:17:04 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=E5=85=85number=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=E4=B8=8E=E5=B9=B3=E5=8F=B0=E4=B8=93=E6=9C=89?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E7=B1=BB=E5=9E=8B=E4=B8=8D=E5=BA=94=E8=AF=A5?= =?UTF-8?q?=E7=9B=B4=E6=8E=A5=E4=BD=BF=E7=94=A8as=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E7=9A=84=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uts/operator.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/uts/operator.md b/docs/uts/operator.md index e3ce6301..23747858 100644 --- a/docs/uts/operator.md +++ b/docs/uts/operator.md @@ -357,6 +357,38 @@ type t = { {"id":1} as t ``` +number数据类型与平台专有数字类型不应该直接使用as转换: +- number转平台专有数字类型应该使用 [Number对象](buildin-object-api/number.md) 的 toXXX 方法转换 +```ts +let a:number = 1; + +let i:Int = a.toInt() // 正确 +let i:Int = a as Int // 错误 + +let f:Float = a.toFloat() // 正确 +let f:Float = a as Float // 错误 + +let d:Double = a.toDouble() // 正确 +let d:Double = a as Double // 错误 + +//系统API需要平台专有数字类型,也应该使用 toXXX 方法转换平台专有数字类型 +systemAPI(a.toDouble()) // 正确 +systemAPI(a as Double) // 错误 +``` +- 平台专有数字类型应该使用 [Number.from()](buildin-object-api/number.md#from) 方法转换 +``` +let i:Int = 1; +let d:Double = 1.0; + +let n:number = Number.from(i) // 正确 +let n:number = i as number // 错误 + +let n:number = Number.from(d) // 正确 +let n:number = d as number // 错误 +``` + +> 虽然在某些情况下使用 as 转换也可以正常工作,但为了保证各平台兼容性推荐使用上述方法转换 + 只允许将类型as为具体或更不具体的类型,不能强制转换两个不可能兼容的类型: ```ts -- GitLab