gpt4 book ai didi

dart - 如何确保始终推断出不可为 null 的类型?

转载 作者:行者123 更新时间:2023-12-01 23:29:27 24 4
gpt4 key购买 nike

我目前正在制作一个 API,我希望类型 T 的可选值never 可以为 null(当然,启用了 null-safety)。

让我们举个例子:

void main() {
T nonNullableGeneric<T>(T value) {
if(value == null) {
throw 'This is null';
}

return value;
}

nonNullableGeneric(1); // Works fine

nonNullableGeneric(null); // Works fine BUT I would like that the type inference would not allow a nullable value

// Now this works as expected:
// "the argument type 'Null' can't be assigned to the parameter type 'int'."
//
// ... but I have to specify the type `T`, which is not clear given my function signature, that clearly
// requires a non-nullable value of type `T`
nonNullableGeneric<int>(null);

// How can I make the following call:
// nonNullableGeneric(null)
// to throw me something like "the argument type 'Null' can't be assigned to a parameter type 'T'."?
}

我还创建了一个 dartpad .

如您所见,如果我想确保在使用泛型参数时它不能为 Null,我必须始终指定类型。

我如何确保它绝不会允许可为 null 的类型?

最佳答案

我发现答案非常明显,尽管我认为无论如何提一下都是合理的:只需将类型 T 约束(扩展)为 Object。这将确保该特定参数永远不会是可选的。

引用 Object 文档:

/// ...
/// Because `Object` is a root of the non-nullable Dart class hierarchy,
/// every other non-`Null` Dart class is a subclass of `Object`.
/// ...

所以,在我提到的这个例子中,解决方案是:

void main() {
T nonNullableGeneric<T extends Object>(T value) {
return value;
}

nonNullableGeneric(1); // Works fine

// Throws a:
// Couldn't infer type parameter 'T'. Tried to infer 'Null' for 'T' which doesn't work: Type parameter 'T' declared to extend 'Object'.
// The type 'Null' was inferred from: Parameter 'value' declared as 'T' but argument is 'Null'.
// Consider passing explicit type argument(s) to the generic
nonNullableGeneric(null);
}

关于dart - 如何确保始终推断出不可为 null 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66574163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com