假设我有下一个接口:
interface TestInterface {
id?: string;
type?: string;
}
当我执行检查时,是否可以重写id!==未定义这将自动意味着也定义了类型属性?
您可以用并集类型来模拟这一点。
简单示例:
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)
。
添加类型保护功能:
你也可以使用类型保护来测试你的标准,并以此方式缩小类型:
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;
}
您可以在Typescript文档中了解更多信息:用户定义类型防护
可重复使用的Empty<T>
:
正如Patrick Roberts在评论中提到的,另一个巧妙的选择是使用映射类型和泛型来制作更可重用的解决方案:
interface INonNullable {
id: string;
type: string;
}
type Empty<T> = {
[K in keyof T]?: undefined;
}
type FinalType<T> = T | Empty<T>;
function testId(x: FinalType<INonNullable>) {
if (x.id !== undefined) {
x.type // string
}
}
让我们看看您的示例:
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
在这种情况下,您对类型检查器说:"嘿,我向您保证objectForTest
不是null
或undefined
"。
这里有一种使用联合的方法:
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
}