创建一个类型,其中每个属性Type现在都属于类型boolean:
type OptionsFlags<Type> = {
[Property in keyof Type]: boolean;
};
Run Code Online (Sandbox Code Playgroud)
现在我想扩展这一点:所有不在 中 Type的属性(如果存在)都必须是类型string。像这样的东西:
type OptionsFlags<Type> = {
[Property in keyof Type]: boolean;
[Property not in keyof Type]?: string;
};
Run Code Online (Sandbox Code Playgroud)
对此正确的做法是什么?
在 Kotlin 中,我们可以像这样使用 Elvis 运算?:符:
val string: String = null ?: "something else"
Run Code Online (Sandbox Code Playgroud)
但是如果“其他东西”是计算的结果呢,比如
val string: String = null ?: {
// do some comutations here
"something else"
}
Run Code Online (Sandbox Code Playgroud)
这不会编译,因为 is 的右侧?:是一个函数() => String而不是String。
我有一种感觉,我需要使用其中一个函数等takeIf,takeUnless但我不明白。
谢谢
现在 Kotlin 中的一些事情让我非常沮丧,我不知道如何解决这个问题:
val map = mapOf(1 to "one")
val value = map[1] // value is String? instead of String
val certainlyNot = map[999] // value is String? instead of compiler error
Run Code Online (Sandbox Code Playgroud)
在我看来,编译器应该能够推断出1键的值类型 String ,并且在尝试访问999键时应该阻止编译。
哪种数据结构更适合我的需求?
编辑:上下文 - >我需要访问像这样的循环中的值
for (key in map.keys) {
val myValue = map[key] // myValue is String?
// but I don't understand why I am forced to do null checks
// when the key in question is certainly in the map …Run Code Online (Sandbox Code Playgroud)