Typescript:未定义的属性转换检查?

问题描述 投票:0回答:1

我们遇到了一个问题,即即使类型不允许,属性也未定义。事实证明,我们创建对象的方式存在一些问题。我做了一个小例子,linter 出于某种奇怪的原因接受了它。我知道如何解决或应该使用这个问题,但我想确保将来不会有这样的陷阱。它允许 joeFriend.kidName 未定义,尽管强制转换为不允许的类型。如果我删除强制转换,它就知道它可能是未定义的。如果我从该对象中删除“kidName”,它也允许它被转换和创建,如果我明确地说kidName:未定义它会显示错误。

type person = {
    name: string;
    kid: { name: string; age: number } | undefined;
};

type friend = {
    name: string;
    kidName: string;
};

const joe = {
    name: "Joe",
    kid: undefined,
} as person;

const joeFriend = {
    name: joe.name,
    kidName: joe.kid?.name,
} as friend;```
typescript undefined
1个回答
0
投票

您遇到此问题是因为您正在转换类型。

TypeScript 假设您在进行类型转换时更了解。这不会引发错误(但应该)

type Person = {
    name: string;
    kid: { name: string; age: number } | undefined;
};

type Friend = {
    name: string;
    kidName: string;
};

const joe = {
    name: "Joe",
    kid: undefined,
} as Person

const joeFriend = {
    name: joe.name,
    kidName: joe.kid?.name,
} as Friend

注意:我使用 PascalCase 声明类型只是为了提高可读性,因为 IDE 可以更好地突出显示语法。

但这会引发错误,因为

joeFriend
未正确设置为
Friend
类型:

const joe: Person = {
    name: "Joe",
    kid: undefined,
}

const joeFriend:Friend = {
    name: joe.name,
    kidName: joe.kid?.name,
}

游乐场

Type 'string | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'.(2322)
input.tsx(8, 5): The expected type comes from property 'kidName' which is declared here on type 'Friend'
© www.soinside.com 2019 - 2024. All rights reserved.