1

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
  • 2
    `Readonly` is the type you want but `readonly` properties don't actually enforce assignability constraints, as per [microsoft/TypeScript#13347](https://github.com/microsoft/TypeScript/issues/13347). Readonly *arrays* are different because they are missing the mutable methods like `push()`, so assignability is different. There's not much to be done here unless you refactor `User` (whatever it is) to, for example, have specific read methods and write methods and no exposed properties, and then manually make a `ReadonlyUser` type that only includes read methods. – jcalz Sep 30 '20 at 19:52
  • 1
    "I don't want to use Readonly because it's not forcing the caller to treat it as Readonly type" then what do you expect `readonly User` to do that is different than `Readonly` ? – Tadhg McDonald-Jensen Sep 30 '20 at 20:17
  • 1
    Does this answer your question? [Why is Readonly assignable to T, but ReadonlyArray is not assignable to Array?](https://stackoverflow.com/questions/54155422/why-is-readonlyt-assignable-to-t-but-readonlyarrayt-is-not-assignable-to-ar) – kaya3 Feb 25 '23 at 22:16

0 Answers0