我如何在打字稿中实现这种类型?

how can i implement this Type in typescript?

type NeedImplement<T,K extends 'key1' | 'key2'> = {
    code: string
    K: T
}

// example should be work
const type1:NeedImplement<number,'key1'> = {
    code: '1',
    key1: 123
}

Q1:如何实现?

Q2:如果默认键是'key1',还需要做什么?

谢谢!

是的,你可以。您必须使用两个 TypeScript 功能:mapped type 和类型交集。

type NeedImplement<T, Keys extends 'key1' | 'key2'> = {
    [key in Keys]: T
} & {
    code: string
}

const type1: NeedImplement<number,'key1'> = {
    code: '1',
    key1: 123
}

请注意,您必须使用类型交集,因为您无法将属性添加到映射类型。