如何根据打字稿中的选项制作一些 属性 键

how to make some property key as required from option in typescript

我有一个 Country 类型和功能如下。我怎样才能创建一个 Country 类型包含所需类型 name 的新类型。所以我没有错误 TS2339: Property 'name' does not exist on type 'Country'.

export type Country<D extends object = {}> =
    | Car<D>;
    | People<D>;

export type People<D extends object = {}> =
    & ValueOf<{
        [K in keyof D]: {
            address: K;
        } & PersonWithOption<D, D[K]>;
    }>;

export interface PersonWithOption<D extends object = {}, V = any> {
    name?: string
}

function setDate(data: Country): Country {
  return data
}

const john = setDate({car: 'tesla', name:'john'})
expect(john.name).to.be('john')
//TS2339: Property 'name' does not exist on type 'Country'.

我试过使用类似

的东西

export type MandateProps<T extends {}, K extends keyof T> = Omit<T, K> & {
    [MK in K]-?: NonNullable<T[MK]>
}
export CountryWithName = MandateProps<Country, 'name'>
function setDate(data: Country | CountryWithName): Country | CountryWithName{
  return data
}

但是我有同样的错误 expect(john.name).to.be('john')

您的 setDate 函数强制将 data 分配给 Country。但是你总是 return Country 而不管 data 是什么类型。

如果你想在不失去特异性的情况下得到执行,那么你需要做的就是使 setDate 成为一个通用函数。此函数检查 typeof data extends Country 但它 return 与提供的类型相同。

function setDate<D extends Country>(data: D): D {
  return data
}
const john = setDate({car: 'tesla', name:'john'})
const name = john.name;

现在可以访问 john.name 因为 john 的类型是 { car: string; name: string; }.

Typescript Playground Link