const program = {
morgning: ['breakfast', 'mingle'],
evning: ['mingle', 'eat', 'party']
} as const
const namespaceEvent = Object.entries(program).reduce(
(acc, [namespace, events]) => [...acc, ...events.map(event => `${namespace}.${event}`)],
[] as string[]
) // can't do 'as const' here;
type Namespace = typeof namespaceEvent[number] // sees the type as 'string' and not "morgning.breakfast" | "morgning.mingle" | "evning.mingle" | "evning.eat" | "evning.party"
const test: Namespace = 'foo.bar' // would like this to error
console.log(namespaceEvent) // ["morgning.breakfast", "morgning.mingle", "evning.mingle", "evning.eat", "evning.party"]
我如何使這項作業,為什么它不起作用?
uj5u.com熱心網友回復:
我認為這是解決此問題的一種方法:
比我想象的要復雜得多,可能有更好的方法!
const program = {
morgning: ['breakfast', 'mingle'],
evning: ['mingle', 'eat', 'party']
} as const
type KV = {[K in keyof typeof program]: `${K}.${typeof program[K][number]}`};
type NS = KV[keyof KV];
// type NS = "morgning.breakfast" | "morgning.mingle" | "evning.mingle" | "evning.eat" | "evning.party"
const namespaceEvent = Object.entries(program).reduce(
(acc, [namespace, events]) => [...acc, ...events.map(event => `${namespace}.${event}`)] as NS[],
[] as NS[]
)
const test: NS = 'foo.bar' // ERROR: Type '"foo.bar"' is not assignable to type 'NS'.
const test1: NS = 'morgning.breakfast' // works
console.log(namespaceEvent) // ["morgning.breakfast", "morgning.mingle", "evning.mingle", "evning.eat", "evning.party"]
見TS Playground:https : //tsplay.dev/WJRV5W
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366076.html
標籤:javascript 打字稿
