Typescript拾取-拾取属性字段
假设我有一个界面,例如:Typescript拾取-拾取属性字段,typescript,Typescript,假设我有一个界面,例如: interface MyInterface { myProperty: { one: number two: string } } 如何选择myProperty字段?这可能吗? 预期结果应为: { one: number two: string } 因此,在使用类型时: type MyType = ... const t: MyType = ... t.one = ... 您可以为myProperty创建单独的接口:
interface MyInterface {
myProperty: {
one: number
two: string
}
}
如何选择myProperty字段?这可能吗?
预期结果应为:
{
one: number
two: string
}
因此,在使用类型时:
type MyType = ...
const t: MyType = ...
t.one = ...
您可以为myProperty创建单独的接口:
interface MyProperty {
one: number
two: string
}
interface MyInterface {
myProperty: MyProperty
}
const myObject: MyProperty = { one: 1, two: "2" };
然后在整个代码中使用它。您可以为myProperty创建单独的界面:
interface MyProperty {
one: number
two: string
}
interface MyInterface {
myProperty: MyProperty
}
const myObject: MyProperty = { one: 1, two: "2" };
然后在整个代码中使用它。如果要获取成员的类型,只需使用类型查询:
interface MyInterface {
myProperty: {
one: number
two: string
}
}
type MyType = MyInterface['myProperty']
const t: MyType = {
one: 1,
two: '2'
};
t.one = 3
尽管按照另一个答案的建议重构为单独的类型可能是更明智的选择 如果要获取成员的类型,只需使用类型查询:
interface MyInterface {
myProperty: {
one: number
two: string
}
}
type MyType = MyInterface['myProperty']
const t: MyType = {
one: 1,
two: '2'
};
t.one = 3
尽管按照另一个答案的建议重构为单独的类型可能是更明智的选择 将它们分离为两个独立的接口
interface MyProperty {
one: number
two: string
}
interface MyInterface {
myProperty:MyProperty
}
将它们分离为两个单独的接口
interface MyProperty {
one: number
two: string
}
interface MyInterface {
myProperty:MyProperty
}
这是一个一次性的东西,对JS模块是私有的,只在一行代码中使用,所以我想我会走这条路。谢谢Titian,有没有办法回到原来的界面?我只是curious@LppEddtl;博士据我所知,没有一种可能是粗俗的方式。财产的类型不知道它起源于何处。您可以构建一个更复杂的类型来提取属性类型,还可以添加额外的信息来保留原始类型,但是您将有一个额外的伪属性,如_parent来保留类型信息,因此除非绝对不可避免,否则我不会使用它。谢谢!无论如何,我不会做任何类似的事情,我只是好奇这是一件一次性的事情,对JS模块是私有的,只在一行代码中使用,所以我想我会走这条路线。谢谢Titian,有没有办法回到原来的界面?我只是curious@LppEddtl;博士据我所知,没有一种可能是粗俗的方式。财产的类型不知道它起源于何处。您可以构建一个更复杂的类型来提取属性类型,还可以添加额外的信息来保留原始类型,但是您将有一个额外的伪属性,如_parent来保留类型信息,因此除非绝对不可避免,否则我不会使用它。谢谢!反正我不会做那样的事,我只是好奇而已