Imagine we have interface
interface Foo {
bar: number | undefined;
}
If we try to create object of type Foo like
const foo: Foo = {};
It won't compile because property bar is missing. But we say that it can be undefined, which will work if we explicitly set it to undefined, but that's exactly same if we do not set it at all. Shouldn't it do exactly same as following?
interface Foo {
bar?: number;
}
For me this is an issue, because if we consider more complex example, where we have interface with a field, which can be optional by generic type. So like, if generic type is not specified, then field should be undefined, if it is specified, then it should be only of that type. For example
interface Foo<T = undefined> {
bar: T;
title: string;
}
const foo1: Foo = {
title: 'TITLE'
};
const foo2: Foo<number> = {
title: 'title',
bar: 12
};
foo1 will fail to compile because property is missing, but it anyway has to be undefined, and if we specify it explicitly it will work, but that's exactly same. I ended up solving this problem with inheritance, where base class doesn't have any generic parameters and the child has it strictly specified. But I am just curious if anyone knows a specific reason why undefined type is handled this way. Because I couldn't find any information about it myself.
Both definitions are exactly the same. If you hover Data1 it the TypeScript Playground, it even expands to the Data2 syntax. It is perfectly fine to use either way, and it's totally up to developer or team preference to decide what they want to choose.
TypeScript provides a Optional parameters feature. By using Optional parameters featuers, we can declare some paramters in the function optional, so that client need not required to pass value to optional parameters.
The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may have a value of undefined . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not undefined before accessing properties.
The two type signatures aren't entirely equivalent (although they're close enough that the difference may not be apparent at first glance)!
bar?: number
expresses that the object might not have a field called bar
.bar: number | undefined
expresses that the object will always have a field called bar
, but the value of that field might be set to undefined
.This difference might matter in some cases, as some runtime behaviors are dependent on the difference between a field being present and a field being set to undefined - consider if you called Object.keys
on the object:
Object.keys({ bar: undefined }) // returns ["bar"]
Object.keys({}) // returns []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With