gpt4 book ai didi

typescript - 输入单个记录条目

转载 作者:行者123 更新时间:2023-12-05 07:10:41 28 4
gpt4 key购买 nike

我正在寻找描述具有单个属性(具有任何值)的对象的 TypeScript 类型定义。

我知道有索引签名,例如

type X = { [key: string]: any }

或者

type X = Record<string, any>

然而这将允许像这样的对象

const obj: X = {
"a": 12,
"b": "c"
}

我正在寻找一种 Y 类型,它限制 obj 具有单个属性,代表一种“RecordEntry”,即

const obj: Y = {
"a": 12
}

应该没问题,但是

const obj: Y = {
"a": 12,
"b": "c"
}

应该被编译器拒绝。

这可能吗?

最佳答案

我不认为这是可能的好方法,这是我能想到的最好的方法:

type NotUnion<T, U = T> =
T extends any ?
[U] extends [T] ? T
: never
: never;

type SingleProperty<T extends {}> =
keyof T extends NotUnion<keyof T> ? T
: never;

const oneProperty = {
a: 'a'
};
const onePropertyAgain: SingleProperty<typeof oneProperty> = oneProperty; // works

const twoProperties = {
a: 'a',
b: 'b'
};
const twoPropertiesAgain: SingleProperty<typeof twoProperties> = twoProperties; // compiler error

你可以像这样让它变得更好一点:

function asSinglePropertyObject<T extends {}>(obj: SingleProperty<T>): SingleProperty<T> {
return obj;
}

const oneProperty = asSinglePropertyObject({
a: 1 // works
});

const twoProperties = asSinglePropertyObject({
a: 1, // Type 'number' is not assignable to type 'never'
b: 'a'
});

关于typescript - 输入单个记录条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61112584/

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