跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[TypeScript] 怎么每次碰到想不通的代码行都出在 TypeScript😢 这行到底哪里有问题?

发表于

服了 TypeScript 这货了,符合我对微软的刻板印象,最近几年似乎每次碰到看不明白的语法出错,都是在 TypeScript ,这货无数细节太微妙了。

interface Elements {
  div: { id: number; name?: string; color: string; x: string }
  a: { id: number; name?: string; href: string; x: string }
}

declare function getProps<T extends Record<any, any>>(obj: T, keys: (keyof T)[]): void

function Foo<T extends 'div' | 'a'>(tag: T, props: Omit<Elements[T], 'x'>) {
  // 这行报错 Type 'string' is not assignable to type 'Exclude<keyof Elements[T], "x">'
  getProps(props, ['id'])
}
Foo('a', { id: 1, href: '#' })

// 我以为是因为 Omit 只能放单个对象,试了下多个也行啊。
type kkk = Omit<Elements['div' | 'a'], 'x'>
把 `function Foo<T extends 'div' | 'a'>(tag: T, props: Omit<Elements[T], 'x'>)` 
改成 `function Foo<T extends 'div' | 'a'>(tag: T, props: Omit<Elements['div' | 'a'], 'x'>)` 就不会报错。
那这个 `T` 不就是 `'div' | 'a'` 吗?这 tm 二者到底有什么微妙区别导致代码一个报错一个没错?

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.