,

,
mail@pastecode.io avatar
unknown
typescript
2 years ago
1.5 kB
2
Indexable
Never
interface Todo {
    title: string
    description: string
    completed: boolean
}

type MyOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

type TodoPreview = MyOmit<Todo, 'description' | 'title'>

const todo: TodoPreview = {
    completed: false,
}


//2


type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type First<T extends unknown[]> = T[0]

type head1 = First<arr1> // expected to be 'a'
type head2 = First<arr2> // expected to be 3

// 3

type Todo = {
    title: string
    description: string
    completed: boolean
}
type MyReadonly2<T, K extends keyof T> = Readonly<Pick<T, K>> & Omit<T, K>

const todo: MyReadonly2<Todo, 'title' | 'description'> = {
    title: "Hey",
    description: "foobar",
    completed: false,
}


todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property
todo.completed = true // OK



// 4

type X = {
    x: {
        a: 1
        b: 'hi'
        z: string
    }
    y: string
}


type Expected = {
    readonly x: {
        readonly a: 1
        readonly b: 'hi'
    }
    readonly y: 'hey'
}

type DeepReadonly<T> = Readonly<{ [key in keyof T]: Readonly<T[key]> }>

type Todo = DeepReadonly<X> // should be same as `Expected`


const test: Todo = {
    x: {
        a: 1,
        b: 'hi',
        z: 'try change me too',
    },
    y: 'try change me',
};


test.y = 'changed'; // Error
test.x.b = 'changed'; // Error