假设我有下一个界面:
interface TestInterface {
id?: string;
type?: string;
}
是否可以通过以下方式重写:当我执行 id!== undefined 检查时,会自动意味着还定义了 type 属性? / p>
答案 0 :(得分:6)
您可以使用联合类型来模仿。
简单示例:
import random
d = {'a':1, 'b':2, 'c':3, 'd':4}
l = list(d.items())
random.shuffle(l)
d = dict(l)
interface INonNullable {
id: string;
type: string;
}
interface INullable {
id?: undefined;
type?: undefined;
}
type FinalType = INonNullable | INullable;
function testId(x: FinalType)
{
if (x.id !== undefined) {
x.type // string
}
}
是可选的,您只需在任何地方使用FinalType
。
添加类型保护功能:
您还可以使用带有类型卫士的功能来测试您的条件并以这种方式缩小类型:
(x: INonNullable | INullable)
您可以在Typescript文档中获得有关此信息的更多信息: User-Defined Type Guards
可重复使用的interface INonNullable {
id: string;
type: string;
}
interface INullable {
id?: undefined;
type?: undefined;
}
type FinalType = INonNullable | INullable;
function isNonNullable(x: FinalType): x is INonNullable
{
return x.id !== undefined;
}
let x = {};
if (isNonNullable(x)) {
x.type // string;
}
:
如Patrick Patricks的评论中所述,另一个巧妙的选择是使用映射类型和泛型来使解决方案更可重用:
Empty<T>
答案 1 :(得分:1)
让我们看看您的示例:
interface TestInterface {
id?: string;
type?: string;
}
const objectForTest: TestInterface = {
id: '12345',
type: 'some type'
}
您可以通过以下方式进行操作:
1)objectForTest?.id
如果此运算符满足undefined
,它将返回该值而不会抛出TypeError
。
这等同于:
const testValue = (objectForTest === null || objectForTest === undefined) ?
undefined
:
objectForTest.id;
2)objectForTest!.id
在这种情况下,您说要输入checker:“嘿,我向您保证objectForTest
不是null
或undefined
”。
答案 2 :(得分:1)
这是一种使用union来完成您想要的事情的方法:
interface IdWithType {
id: string;
type: string;
}
interface WithoutId {
id?: never;
type?: string;
}
type TestInterface = IdWithType | WithoutId
// You cannot instansiate an object of type TestInterface with an id and with out a type
const yo: TestInterface = { // Type '{ id: string; }' is not assignable to type 'TestInterface'.
id: "hey"
}
const testFunction = (a: TestInterface) => {
if (a.id) {
const b = a.type // string
}
const c = a.type // string | undefined
}