admin管理员组文章数量:1406321
TS v3.x brought new type: unknown
. But it's not very clear how to easily use this type instead of any
.
Example: you're using some 3rd party library which has no types. And you don't have time to write those types yourself. You need to handle some data provided by that library.
Before unknown
:
function handle(data: any) {
if (data && data.arrayProp && typeof data.arrayProp[Symbol.iterator] === 'function') {
for (let x of data.arrayProp) {...}
}
}
With unknown
:
function handle(data: unknown) {
// this line gives TS error: `data` is unknown type
if (data && data.arrayProp && typeof data.arrayProp[Symbol.iterator]=== 'function') {
...
Most docs in internet are using kind of instanceof
ways to check what type data
has. But i'm not really interested what type data
has. Everything i want to know is if there's arrayProp
there. that's it
How to do this with unknown
type?
TS v3.x brought new type: unknown
. But it's not very clear how to easily use this type instead of any
.
Example: you're using some 3rd party library which has no types. And you don't have time to write those types yourself. You need to handle some data provided by that library.
Before unknown
:
function handle(data: any) {
if (data && data.arrayProp && typeof data.arrayProp[Symbol.iterator] === 'function') {
for (let x of data.arrayProp) {...}
}
}
With unknown
:
function handle(data: unknown) {
// this line gives TS error: `data` is unknown type
if (data && data.arrayProp && typeof data.arrayProp[Symbol.iterator]=== 'function') {
...
Most docs in internet are using kind of instanceof
ways to check what type data
has. But i'm not really interested what type data
has. Everything i want to know is if there's arrayProp
there. that's it
How to do this with unknown
type?
1 Answer
Reset to default 5The thing with unknown
is that you have to narrow its type before you can use it. You can use a custom type guard for this:
interface ArrayProp {
arrayProp: []
}
function isArrayProps(value: unknown): value is ArrayProp {
return !!value && !!(value as ArrayProp).arrayProp;
}
function handle(data: unknown) {
if (isArrayProps(data) && typeof data.arrayProp[Symbol.iterator] === 'function') {
}
}
Playground
本文标签: javascriptTypescript Check if methodproperty exists in the variable of unknown typeStack Overflow
版权声明:本文标题:javascript - Typescript. Check if methodproperty exists in the variable of unknown type - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745004893a2637201.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论