我想要实现的是:
type Post = {
id: number
title: string
author: {
name: string
}
comments: {
text: string
}[]
}
type ExtractPathExpressions<T> = ???
type Paths = ExtractPathExpressions<Post>
// expects above got a union --> 'id' | 'title' | 'author' | 'author.name' | 'comments' | `comments[${number}]` | `comments[${number}].text`
Run Code Online (Sandbox Code Playgroud)
我知道这很不寻常......但是,有人知道它会是什么样子吗ExtractPathExpressions?
我知道我可以使用object关键字输入“对象” ,但是如何在不使用any关键字的情况下将其输入为“任何对象” ?(因为any将允许任何原始类型,如字符串或数字)。
let a:object;
a.foo // error: Property 'foo' does not exist on type 'object'.
Run Code Online (Sandbox Code Playgroud) 我正在阅读https://www.typescriptlang.org/docs/handbook/2/conditional-types.html
我想知道为什么这行不通?
interface IdLabel {
id: number
}
interface NameLabel {
name: string
}
type NameOrId<T extends number | string> = T extends number
? IdLabel
: NameLabel;
function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
if (typeof idOrName === 'number') {
return { id: 1 }
} else {
return { name: 'foo' }
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这会起作用(这是文档给出的示例),但这完全没用,甚至不返回任何值......
function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
throw "unimplemented";
}
Run Code Online (Sandbox Code Playgroud)
条件类型是否仅适用于“类型定义”..?
我可以在vue3的setup函数中引用css模块中的类名吗?
<script setup>
console.log(this.$style.myClass) // this won't work
</setup>
<style lang="scss" module>
.myClass {
}
</style>
Run Code Online (Sandbox Code Playgroud)