首页 > 解决方案 > 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

标签: javascriptarraystypescriptreadonly

解决方案


推荐阅读