如何获得期权财产

interface Input {
    necessaryA: string;
    necessaryB: string;
    optionA?: string;
    optionB?: string;
}

type defaultInputProperty = {
    optionA: string;
    optionB: string;
}

function handle(input: Input) {
    const defaultvalues: defaultInputProperty = {
        optionA: 'defaultA',optionB: 'defaultB',}
    const actualInput: Required<Input> = { ...defaultvalues,...input };
    // do something with actualInput
}

如何声明defaultInputProperty,以便在Input的声明更改时正确?
更具体地说,defaultInputProperty需要添加属性optionC,而Input具有新的选项属性optionC并且defaultInputProperty不需要添加属性{{1} },当necessaryC具有新的必要属性Input时。
换句话说,necessaryCdefaultInputProperty中具有所有选项属性,而在Input中则没有必要的属性。

chibi452 回答:如何获得期权财产

如果我正确理解了您的问题,那么您应该可以这样定义它:

type OptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? K : never }[keyof T];

type defaultInputProperty = {
    [K in OptionalKeys<Input>]: Exclude<Input[K],undefined>;
}

如果启用了编译器标志strictNullChecks,此方法将起作用。

defaultInputProperty将具有以下类型:

type defaultInputProperty = {
    optionA: string;
    optionB: string;
}

编辑:-? 的说明

启用--strictNullChecks时,可选参数和属性的类型会更改。参考:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#optional-parameters-and-properties

以下内容:

interface Input {
    necessaryA: string;
    necessaryB: string;
    optionA?: string;
    optionB?: string;
}

成为

interface Input {
    necessaryA: string;
    necessaryB: string;
    optionA?: string | undefined;
    optionB?: string | undefined;
}

如果我们省略-?,则OptionalKeys<Input>表示以下类型:

"optionA" | "optionB" | undefined

当我们尝试在defaultInputProperty的{​​{1}}中使用它时,由于属性名称不能为[K in OptionalKeys<Input>]

,它会给出一个错误Type '"optionA" | "optionB" | undefined' is not assignable to type 'string | number | symbol'.。 >

如果我们将undefined.定义为OptionalKeys<T>,那么-?的意思是:

OptionalKeys<Input>

对此的解释可以在TypeScript 2.8发行说明中找到,该发行说明更详细地描述了"optionA" | "optionB" 映射类型修饰符:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#improved-control-over-mapped-type-modifiers

  

请注意,在?模式下,当同态映射类型从基础类型的属性中删除--strictNullChecks修饰符时,也会从该属性的类型中删除?:>

undefined
本文链接:https://www.f2er.com/3069153.html

大家都在问