javascript - Why readonly can be used only on array and tuple types?
问题描述
Why I am not able to return a readonly type for an object like I am able to do for array/tuple references?
async function getUsersByName (name: string): readonly User[] {
return db.User.query(name);
}
The above forces the caller to use readonly on the declared type.
const users: User[] = await getUsersByName("foo"); // error
const users: readonly User[] = await getUsersByName("foo"); // correct
If I try to use readonly on an object type then an error is thrown saying that it can be used only on arrays/tuples.
async function getUserByName (name: string): readonly User { // error
return db.User.query(name);
}
Why I am not able to use readonly in this case? I don't want to use Readonly<T>
because it's not forcing the caller to treat it as Readonly type and it makes no sense to me.
async function getUserByName (name: string): Readonly<User> {
return db.User.query(name);
}
const user: User = await getUserByName("bar"); // correct
const user: Readonly<User> = await getUserByName("bar"); // correct
解决方案
推荐阅读
- webpack - “main”和“renderer”文件夹“electron-webpack”有什么区别?
- php - 用户购买 WooCommerce 会员订阅后的 wp_insert_post
- django - CREATE 上 DRF 中的多部分图像上传
- powershell - Powershell函数在第一次调用时不起作用
- google-bigquery - 无法在旧版 SQL 查询中引用标准 SQL 视图 - GBQ & IICS
- azure - 日本东部地区的认知 OCR 服务停止工作
- python - 如何在 Tensorflow 中对 10% 的数据集进行采样?
- xcode - 无法使用类型为“(键:字符串)”的索引为类型为“JSON”的值下标
- postgresql - PSQL:无法输入密码
- gnuplot - 在 gnuplot 中绘制两个二维图,一个在另一个之上