admin管理员组

文章数量:1124406

I found the following generic type in some codebases:

type MyType<T> = {[K in keyof T]: T[K] }

Why is it not the same as type MyType<T> = T?

I tried to find the difference in the types/values keyof MyType<SomeOtherType> can have, but failed, are there other implications to the first Type definition?

/* eslint-disable @typescript-eslint/no-unused-vars */
type BaseType = {
    a: number
    b: string
}

type MyTypeA<T> = {
    [K in keyof T]: T[K]
}

type MyTypeB<T> = T

function MyFuncA<T extends BaseType>(a: MyTypeA<T>, key: keyof T) {
    const c = a[key]
    return c
}

function MyFuncB<T extends BaseType>(a: MyTypeB<T>, key: keyof T) {
    const c = a[key]
    return c
}

type ExtendedType = BaseType & {
    c: boolean // additional property
}

const extendedObject: ExtendedType = {
    a: 1,
    b: 'test',
    c: true,
}


const CA = MyFuncA(extendedObject, 'a') // CA  has type "number | sting | boolean"


const CB = MyFuncB(extendedObject, 'a') // CA  also has type "number | sting | boolean"

本文标签: typescriptWhat is the diference between quotK in keyof T TK quot and just quotTquotStack Overflow