面试题答案
一键面试- Kotlin与TypeScript基本数据类型对应关系
- 数值类型:
- Kotlin的
Int
对应TypeScript的number
(在TypeScript中,没有专门区分32位整数等概念,number
统一表示所有数字类型)。例如,Kotlin中的val num: Int = 10
,在TypeScript中可以表示为let num: number = 10
。 - Kotlin的
Long
也对应TypeScript的number
,因为JavaScript本身没有64位整数类型,在TypeScript中也统一用number
处理。 - Kotlin的
Float
和Double
同样对应TypeScript的number
。
- Kotlin的
- 字符串类型:Kotlin的
String
对应TypeScript的string
。如Kotlin中val str: String = "Hello"
,TypeScript中let str: string = "Hello"
。 - 布尔类型:Kotlin的
Boolean
对应TypeScript的boolean
。Kotlin中val bool: Boolean = true
,TypeScript中let bool: boolean = true
。
- 数值类型:
- 在Kotlin/JS代码中声明函数接收TypeScript字符串类型参数并返回Kotlin整数类型结果示例
@JsExport
fun convertStringToInt(str: String): Int {
return str.toIntOrNull() ?: 0
}
在上述代码中,@JsExport
注解使得该函数可以在JavaScript(包括TypeScript)环境中被调用。函数接收一个String
类型的参数str
,尝试将其转换为Int
类型,如果转换失败则返回0。在TypeScript中调用该函数的示例代码如下:
import { convertStringToInt } from './yourModule'; // 假设Kotlin代码编译后的模块名是yourModule
const result = convertStringToInt('123');
console.log(result);