gpt4 book ai didi

typescript :将必需的属性转换为可选的

转载 作者:行者123 更新时间:2023-12-02 00:30:25 25 4
gpt4 key购买 nike

如何将非可选属性转换为可选属性?这是代码:

interface Foo {
bar: any // no '?', hence this prop is required
}

type KeysOfFoo = {
[K in keyof Foo]: any
}

const keysOfFoo: KeysOfFoo = {} // No tsc error wanted here, got: "type '{}' is not assignable to type KeysOfFoo"

最佳答案

这里只是一个变化,虽然它不适用于问题中的问题。这里的解决方案也保留了键的类型。在这里阅读更多:https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types

interface Foo {
bar: any // no '?', hence this prop is required
}

type KeysOfFoo = {
[K in keyof Foo]?: Foo[K] // so that it retains the types
}

关于 typescript :将必需的属性转换为可选的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52142932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com