最初我得到了这些错误
server.ts:30:12 - error TS2339: Property 'shop' does not exist on type 'Session | null'.
30 const {shop, accessToken} = ctx.session;
~~~~
server.ts:30:18 - error TS2339: Property 'accessToken' does not exist on type 'Session | null'.
30 const {shop, accessToken} = ctx.session;
~~~~~~~~~~~
在写了const {shop, accessToken} = ctx.session as {shop: string, accessToken: string}
之后,我看到了以下内容:
server.ts:48:31 - error TS2352: Conversion of type 'Session | null' to type '{ shop: string; accessToken: string; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Type 'Session' is missing the following properties from type '{ shop: string; accessToken: string; }': shop, accessToken
48 const {shop, accessToken} = ctx.session as {shop: string, accessToken: string};
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[4:52:59 AM] Found 4 errors. Watching for file changes.
我是Typescript的新手,但相信我有两个选项
- 将行重写为
const {shop, accessToken} = ctx.session as unknown as {shop: string, accessToken: string}
- 为
Session
编写一个接口,并对其断言ctx.session(ctx.session as Session
(,覆盖以前的类型赋值(session|null(
这是正确的吗?这里有什么更好的选择?
问题是"session"可以为null,而null不包含任何属性。
试试其中一个:
const {shop, accessToken} = ctx.session!;
或者:
if (ctx.session === null) { return; } // Or throw, or next()
const {shop, accessToken} = ctx.session;