Typescript "keyof typeof" types derived from objects?

39 Views Asked by At

Can anyone explain the typescript "keyof typeof" behavior illustrated in the examples below and perhaps suggest a workaround:

// Test the behavior of the keyof operator 
// deno --version
//      deno 1.40.3 (release, x86_64-pc-windows-msvc)
//      v8 12.1.285.6
//      typescript 5.3.3

// Working example
const kRec = {
    k1: 'k1',    
    k2: 'k2',
    k3: 'k3',
    k4: 'k4',
}

// This returns: "k1" | "k2" | "k3" | "k4"
type _kRecFieldsType = keyof typeof kRec

// Same, but with a type definition
type KRecType1 = Record< string, string>

const kRec1: KRecType1 = {
    k1: 'k1',    
    k2: 'k2',
    k3: 'k3',
    k4: 'k4',
}

// This returns: string
type _kRecFieldsType1 = keyof typeof kRec1


// Same, but with another type definition
type KRecType2 = { [ key: string ]:   string }

const kRec2: KRecType2 = {
    k1: 'k1',    
    k2: 'k2',
    k3: 'k3',
    k4: 'k4',
}
// This returns: string | number
type _kRecFieldsType2 = keyof typeof kRec2

Running the 3 examples I expected to see the same generated type.

0

There are 0 best solutions below