MST
星途 面试题库

面试题:Kotlin中Kotlin/JS与TypeScript基本类型互操作问题

在Kotlin/JS与TypeScript互操作场景下,简述Kotlin的基本数据类型(如Int、String等)如何与TypeScript的对应类型进行交互?请举例说明如何在Kotlin/JS代码中声明一个函数接收TypeScript的字符串类型参数并返回Kotlin的整数类型结果。
18.6万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
  1. 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的FloatDouble同样对应TypeScript的number
    • 字符串类型: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
  2. 在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);