[英]How to write types / or use use types for flatten object key in typescript?
考虑这种情况
interface abc {
a: { b: string }
}
const test: abc = { a: { b: 'string'} }
test['a.b'] = 'new string' // error type a.b doesnt exists
https://codesandbox.io/s/delicate-night-9u5ps?file=/src/index.ts
如何解决这个错误? 如何使用已经定义的类型并仍然使用 flatten 键?
PS:我不能像 test.ab 一样使用它
我们希望看到 Typescript 在这里所做的是将一组密钥转换为另一组密钥。 有一些方法可以做到这一点,例如Pick
:
interface IA {
a: number;
b: number;
c: boolean;
}
const x: Pick<IA, 'a' | 'b'> = {
a: 1,
b: 2,
c: 3, // type error here as we're not picking that property
}
在此示例中,Typescript 能够基于选择某些指定键在键集['a', 'b', 'c']
和['a', 'b']
之间进行转换。 我们还可以扩展对象的键:
type TestExtentionType = IA & { d: number };
const y: TestExtentionType = {
a: 1,
b: 2,
c: true,
d: 4,
}
我们需要类型系统来做,为了让 typescript 自动确定您正在寻找的返回类型,是能够 go 从key, key
到'key.key'
,或更一般地说,我们需要 Typescript 的类型系统才能连接字符串文字。 在我写这篇文章的时候,似乎不可能让 typescript 做到这一点。
我可以看到接近您需要的唯一选择是使用扁平键定义特定类型:
interface abc {
a: { b: string }
}
interface abcFlattened {
'a.b': string;
}
const flattenAbc = (x: abc): abcFlattened =>
// do the flattening
其他选项涉及完全重写您正在做的事情; 如果您想将该键作为“ab”,那么我不知道还有其他方法可以做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.