Skip to main content

Get Readonly Keys

introduction#

Implement a generic GetReadonlyKeys<T> that returns a union of the readonly keys of an Object.

For example

ts
interface Todo {
readonly title: string;
readonly description: string;
completed: boolean;
}
type Keys = GetReadonlyKeys<Todo>; // expected to be "title" | "description"
ts
interface Todo {
readonly title: string;
readonly description: string;
completed: boolean;
}
type Keys = GetReadonlyKeys<Todo>; // expected to be "title" | "description"
View on GitHub

start point#

ts
/* _____________ Your Code Here _____________ */
type GetReadonlyKeys<T> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<'title', GetReadonlyKeys<Todo1>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<'title' | 'description', GetReadonlyKeys<Todo2>>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
 
interface Todo1 {
readonly title: string;
description: string;
completed: boolean;
}
 
interface Todo2 {
readonly title: string;
readonly description: string;
completed?: boolean;
}
Try
ts
/* _____________ Your Code Here _____________ */
type GetReadonlyKeys<T> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<'title', GetReadonlyKeys<Todo1>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<'title' | 'description', GetReadonlyKeys<Todo2>>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
 
interface Todo1 {
readonly title: string;
description: string;
completed: boolean;
}
 
interface Todo2 {
readonly title: string;
readonly description: string;
completed?: boolean;
}
Try
take the challenge

my solutions#

Spoiler warning // Click to reveal answer
ts
type GetReadonlyKeys<T> = keyof {
[K in keyof T as Equal<{ [_ in K]: T[K] }, { readonly [_ in K]: T[K] }> extends true
? K
: never]: 1;
};
Try
ts
type GetReadonlyKeys<T> = keyof {
[K in keyof T as Equal<{ [_ in K]: T[K] }, { readonly [_ in K]: T[K] }> extends true
? K
: never]: 1;
};
Try
view more solutions