且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

打字稿对象:如何将键限制为特定字符串?

更新时间:2023-01-19 21:15:49

您可以使用?将键设置为可选,所以

You can use the ? to make the keys optional, so

interface Partial {
   a?: boolean;
   b?: boolean;
   c?: boolean;
}

或者,您可以执行以下操作:

Or, you can do this:

type Keys = "a" | "b" | "c";

type Test = {
    [K in Keys]?: boolean
}